Friday, September 19, 2014

Android: adding a Spinner (drop-down or pick-list widget)

You start by adding Spinner UI to your res/layout/activity_xyz.xml
Make sure to give it a meaningful ID, especially if you have multiple Spinner items.

            android:id="@+id/conversionSelectorSpinner" />

If your spinner will have a pre-defined list of items that will need to be translated to another language then you probably should use string-array in res/values/strings.xml

    <string-array name="conversionTypeArray">
        <item>meters to yards</item>
        <item>kilometers to miles</item>

In your Activity class you have to add your Spinner in onCreate() method.

   protected void onCreate(Bundle savedInstanceState) {
      //set up the conversion choices using a Spinner
      Spinner conversionSelectorSpinner = (Spinner) findViewById(;
      // create adapter from the res/values/strings.xml/string-array
      // simple_spinner_item is a TextView
      ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.conversionTypeArray, android.R.layout.simple_spinner_item);
     // simple_spinner_dropdown_item is basically a single line TextView that serves as header of a Spinner
       // set array adapter to populate the spinner

Now if you build  the APK we will have a Spinner, but we will have to make it work for us.

We will need a variable that will hold our selection, we will make it a class member to be used in various methods.

public class MainActivity extends ActionBarActivity {
   private int selectedConversion = 0;

We will need a programmatic access to the string-array we defined, we will add that line inside our onCreate() method.

 final String conversionTypeArray[] = getResources().getStringArray(R.array.conversionTypeArray);

Finally, we will have to add a event listener to our Spinner.

      // add listener that will react when an item was selected
      conversionSelectorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
         public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            // assign selected item to the class member to be used later
            selectedConversion = position;
            // if you change conversion type, it is natural that the result will be different
            // we would not have debug toasts in production version, for edu purposes only
            showToast("onItemSelected in position: " + position + " id: " + id + " selected name: " + conversionTypeArray[position]);
         public void onNothingSelected(AdapterView<?> parentView) {
            // onNothingSelected is a Callback method to be invoked when the selection disappears from this view.
            // The selection can disappear for instance when touch is activated or when the adapter becomes empty.