Android for Beginners
About Lesson

Spinners in Android are similar to drop-down menus that we see in other programming languages. They are used to display a list of items from which the user can select one. In this blog, we’ll learn how to use Spinners in an Android app using Java.

 

Creating a Spinner

To create a Spinner, you first need to define it in your layout file:

<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

Populating the Spinner

To populate the Spinner with data, you need to create an ArrayAdapter and set it to the Spinner. Here’s how you can do it:

Spinner spinner = findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

 

In the above code, R.array.planets_array is an array resource defined in res/values/arrays.xml:

<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>

 

Handling Spinner Selections

To handle the selection of items in the Spinner, you need to set an OnItemSelectedListener to the Spinner:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selected = parent.getItemAtPosition(pos).toString();
Toast.makeText(parent.getContext(), "Selected Planet: " + selected, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});

 

In the above code, when an item is selected, a Toast message is displayed showing the selected item.