How To Use Spinner in Android Application Development

Tochukwu Munonye
HackMobile
Published in
3 min readDec 20, 2020

--

The spinner is an android widget which enables a user make a selection out of a list of options. The spinner behaves like a radio group but if you have a lot of options, radio group would be a bad choice because every radio button will occupy space on your screen. The spinner solves this problem because it is just a dropdown view that shows all available options attached. In the default state, a spinner shows its currently selected value.

In this tutorial we are going to make a spinner that displays all the days of the week. Since we know we know all the days of the week, we will use a string array which we’ll declare in the string.xml file to reduce boiler plate code(unnecessary code).

We’ll start by declaring all the days of the week in the string.xml file. To do that go to Res –> Values –> String.xml file. We add a tag called string-array and give it a name “days” so we can later access it in code. Then we open a second nested tag called items for each value(day of the week).

We move over to the layout.xml file and insert the spinner. We set the layout width and height to wrap_content to conserve space, we also set the constraints to keep the spinner fixed to the position we want. Then we use attributes “android:entries” to give the spinner access to the values in our string.xml file.

Next is the big question, how can we detect whenever the currently selected item changes? That’s simple. In our mainActivity.kt file, we call our spinner’s id and call onItemSelectedListener on it. Then we assign it to an anonymous class “AdapterView.onItemSelectedListener”. After this we’ll notice the object is underlined in red because we haven’t implemented the functions defined in AdapterView.onItemSelectedListener. We can simply do that by pressing CTRL + I, hold down shift and select both options. Next we’ll use a toast in onItemSelected function to indicate an item has been selected.

We can also set the entries to the spinner if we only know the values at runtime, without defining the entries in the string array. Here we first declare a list for the spinner in a variable. Then we’ll an adapter for the spinner. In the array adapter we’ll make use of a default spinner layout file called R.layout.support_simple_spinner_dropdown_item. Then we pass the customList variable in the constructor of the ArrayAdapter, then assign adapter variable to the spinner widget.

Happy coding, guys !

--

--