Spinner is simply a dropdown list containing items we can choose. Spinner is made to ease users selecting one value from a list/array that's presented quickly.
How to create Spinner on Android using Android Studio
Basically there are two methods to use for creating Spinner in Android based on data source that we want to present.
First method, using array data that is stored in the resource .xml file in the form of string-array. This method is useful if the list value on Spinner has static behavior -- Not being changed.
Second method, to create Spinner in Android using array data stored in Java file, in form of String array or String ArrayList. This second method is useful if we want to present dynamic data on the list. For example like fetching array from server first before being presented to Spinner.
Method 1. Creating Spinner on Android using String-Array in XML
Step 1 -- Here we will create Spinner with list data stored in XML file as string-array.
Step 2 -- First off, we need to create a new project first using Android Studio. Visit this page to learn to do it.
Step 3 -- After that, we need to open strings.xml file on res/values folder, then enter the string-array as follow.
Step 4 -- The next step is, on activity_main.xml layout we need to add a Spinner view and a button to become like this:
Step 5 -- Now the question is: "How to fetch the selected value on Spinner?" The answer is very simple, simply open MainActivity.java file and do a logic coding there.
Step 6 -- The following is the example code on MainActivity.java.
That's it. Because the Spinner has already being filled with list from XML, so when we click on the Button, we simply call getSelectedItem() method that automatically fetch which item we have selected and change it into String with toString() method.
Now we go to the second method.
Method 2. Creating Spinner using dynamic data like String Array / ArrayList
In this second method we don't need to add string-array on xml resource, because the data list for the Spinner will be fetched directly from its Activity in the form of Array / ArrayList. We will use SpinnerAdapter that allows us to manage array data string so can be displayed on Spinner.
Step 1 -- Firstly we need to add one more Spinner view in the activity_main.xml, like this.
Step 2 -- And the main codes on MainActivity.java file as follow.
Step 3 -- If we look carefully from the above code, the new thing added is String array containing data to be used in the Spinner.
For us to be able monitoring Spinner state when a user finished selecting an item on Spinner. Then it will show Toast containing the selected Spinner item value.