Working with Spinner in Android (Single Selector)

Spinner

Spinners provide a quick way to select one value from a set then we called it a single selector. A spinner shows its currently selected value from set. In the default state, it shows 0 index value from a set. Touching the spinner displays a dropdown menu or dialog with all other available values in the set, So we can be called it a dropdown.

Dropdown

 

 

 

 

 

 

Let’s check, how we can use it in an application.

Spinner integration has 3 key classes:-

1.  Spinner

2. Spinner Adapter

3. Spinner OnItemSelectedListener

So we will discuss above these classes also, with integration. You can add a spinner to your layout XML file. You can use the below sample code –

Spinner Adapter uses for bind between data set and spinner widget and it manages view for the spinner row item. We can use data as an array of string. See sample code –

Above string array, we will use for the display. So now we need to get reference Spinner which we defined in the XML file. We can use the below sample code –

So now we need to set values in ArrayAdapter. and We set this ArrayAdapter in Spinner. Use below code –

When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event. for manage event, we can use OnItemSelectedListener in the Spinner. Sample code –

onItemSelected gives us a selected position of the spinner.

That’s it. Happy Coding 🙂

Reference:-

https://developer.android.com/guide/topics/ui/controls/spinner#java