Recipe 3.6 Displaying a List of Items Using the Spinner View
In addition to using the ListView to display a list of items, you can also use the Spinner view. The Spinner behaves like the drop-down listbox that is popular in the Windows OS. This recipe demonstrates how to use the Spinner.
Solution
For this recipe, let’s use the Spinner view to display a list of names, specifically a list of US presidents.
To use the Spinner, add the <Spinner> element to the UI, such as the activity_main.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true" />
</RelativeLayout>
In the activity, obtain a reference to the Spinner in your UI and assign it to an ArrayAdapter object:
package net.learn2develop.spinner;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
Spinner s1;
String[] presidents = {
"Dwight D. Eisenhower", ...
Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.