The spinner view (control) is the UI element that provides Android’s version of a drop-down control.
Here is an example of code that binds values to a spinner.
The containing class contains the following declarations:
Let’s walk through this code. The first line of the bindAnimalTypes method calls into the application’s data layer to get the name of each type of animal and return those names in a simple ArrayList<String> type. This array will be bound to the _animalTypesField spinner for display. An ArrayAdapter<String> object is created from the array of animal type names, and a standard simple_spinner_item view will be used to display each bound element in the spinner view.
The spinner being created here must have an entry in the list that allows the user to specify that they would like to create a new animal type name. The spinner’s add method is perfect for this since it will add the specified text as the last entry in the spinner’s displayed list of items. Next, the view that is to be used to display the spinner is specified in the call to setDropDownViewResource, in which the standard simple_spinner_dropdown view is specified. You could, of course, create your own custom views to display the spinner and each list item with if you wanted to.
The bulk of the code to bind the animal type names to this spinner consists of determining the position of the already-selected animal name (if any) and telling the spinner to mark that entry. If the app does not already have an animal type name that has been specified then this method is complete and the spinner is ready to be displayed. Otherwise, the method loops through the animal type names array to find the index of the already-selected animal type name and the spinner’s setSelection method is called to specify that entry in the spinner list.
When an item from the spinner is selected, the onItemSelected method specified in the anonymous method passed to the spinner’s setOnItemSelectedListener is called. This method retrieves the list entry that was selected in the spinner and if the name specifies the last entry—which means that a new animal type name should be created—then another dialog view is displayed to allow the user to specify the new animal type name.
That’s it! A fully functional Android spinner (a/k/a drop-down control) with the ability to indicate that a new list choice should be created.