Recientes

Spinner and its data behind

I got another comment asking about Spinner and the data behind the widget. The author of the comment wanted to know, how to associate data to the item the Spinner displays. Then that associated data would be used to look up some other data source.

Click here to download the example program.

In order to understand the trick, one has to know, how Adapters work in general and ArrayAdapter in particular. Adapters are objects that are able to turn data structures into widgets. The widgets are then displayed in a List or in a Spinner. So the two questions an Adapter answers are:

  • What widget or composite view to associate with a data structure with a certain index.
  • How to extract data from the data structure and how to set field(s) of the widget or composite view according to this data.
ArrayAdapter's answers are:
  • Each widget for any index is the same and is inflated from the resource whose ID the ArrayAdapter receives in its constructor.
  • Each such a widget is expected to be an instance of TextView (or descendant). The widget's setText() method will be used with the string format of the item in the supporting data structure. The string format will be obtained by invoking toString() on the item.
Knowing these facts, the solution is very simple. We back ArrayAdapter with our own data structure. In this simple example MyData structure has just two fields but we can use structures with arbitrary complexity. The only thing we have to care about is that the data object's toString() method will be used to obtain the text which is displayed in the Spinner. Hence we made sure that toString() returns just one field of the object. The other field will be retrieved from MyData when the item is selected. Our application is written in such a way that then the other field is displayed in a separate text field.






Comentarios 1 link Destacados

Comentarios 1 link Destacados