Android Spinner – mimic the HTML dropdown behavior – Mea Cup O' Jo
Skip to content


Android Spinner – mimic the HTML dropdown behavior

To my dismay I found out that out of the box Android’s Spinner only supports String values for its items. Yes – you can write a custom SpinnerAdapter to support any type of object but if you are just looking for HTML-list type of functionality where you can provide both – label and value for the item there’s a simpler way:

  • Define your Spinner as usual in your layout.xml
  • Add 2 array sections to your array.xml: one for labels, other one for values
  • The values array can be String or Integer the key – you should have same number of entries in the corresponding order between 2 arrays
  • Add labels array to the Spinner definition as
    <Spinner android:entries="@arrays/labels"/>
  • In your code, whenever you need to get value for the selected Spinner item, get it form the value array as follows:
        String selectedVal = getResources().getStringArray(
            R.array.values)[spinner.getSelectedItemPosition()];
    

Posted in Android.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.