A Spinner is a widget that allows the user to select an item from a group.
It is similar to a dropdown list and will allow scrolling when the
list exceeds the available vertical space on the screen.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Please select a planet:"
/>
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:prompt="@string/planet_prompt"
/>
</LinearLayout>
Notice that the Spinner's android:prompt is a string resource. In
this case, Android does not allow it to be a string, it must be a reference to a resource.
So...
<string>
element inside the <resources> element:
<string name="planet_prompt">Choose a planet</string>
<resources>
<string-array name="planets">
<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>
This is the list of items (planets) that the user can select from in the Spinner widget.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.planets, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
}
That's it. We start by creating a Spinner from our layout. We then create an ArrayAdapter
that binds each element of our string array to a layout view—we pass createFromResource our Context,
the array of selectable items and the type of layout we'd like each one bound to. We then call
setDropDownViewResource() to define the type of layout in which to present the
entire collection. Finally, we set this Adapter to associate with our Spinner,
so the string items have a place to go.
It should look like this: