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.

        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            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>
    </string-array>


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

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
     
      //set up the conversion choices using a Spinner
      Spinner conversionSelectorSpinner = (Spinner) findViewById(R.id.conversionSelectorSpinner);
     
      // 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
      adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     
       // set array adapter to populate the spinner
      conversionSelectorSpinner.setAdapter(adapter);



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() {
         @Override
         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
            calculateResult();
            // we would not have debug toasts in production version, for edu purposes only
            showToast("onItemSelected in position: " + position + " id: " + id + " selected name: " + conversionTypeArray[position]);
         }
         @Override
         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.
            showToast("onNothingSelected");
         }
      });