Android Spinner

January 12, 2018 Oclemy Android Spinner 2 minutes, 18 seconds

Spinner is a view that displays items in a dropdown fashion, allowing user to pick one at a time.

Android Spinner

Spinner is an AdapterView. This means that it relies on an Adapter for its data.

Adapters act as the bridge between adapterviews and the underlying data source.

This makes Spinner like other adapterviews decoupled from data source. Hence we can customize the views shown in the spinner without affecting data.

Spinner is a concrete public class residing in the android.widget package.

package android.widget;

Spinner is a public class that's why we can access and use it.

public class
Spinner{}

Public classes are visible even from other packages apart from those they've been defined.

Spinner class inherits from an abstract class called AbsSpinner. This class also resides in the android.widget package.

AbsSpinner provides to Spinner much of the capabilities it has. For example, Spinner is an adapterview since it derives from the AbsSpinner. This allows Spinner to set and return a SpinnerAdapter.

Adding Spinner in Layout

We can use the Spinner object to specify the spinner in an xml layout.

<Spinner
    android:id="@+id/mySpinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

Populating Spinner

Then in our java code we can first reference the Spinner from our layout specification using the findViewById() method our activity class.

Spinner spinner = (Spinner) findViewById(R.id.mySpinner);

We can then instantiate a SpinnerAdapter(e.g ArrayAdapter). We use the default spinner layout(android.R.layout.simple_spinner_item).

We are using a static method called createFromResource(). This method is provided by the ArrayAdapter class and it returns us an ArrayAdapter instance from the external resource we provide it as our data source.

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.galaxies_array, android.R.layout.simple_spinner_item);

You have to make sure you've added string array into your strings.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="galaxies_array">
        <item>Milky Way</item>
        <item>Andromeda</item>
        <item>Whirlpool</item>
        <item>Sombrero</item>
        <item>Cartwheel</item>
        <item>StarBust</item>
        <item>Pinwheel</item>
        <item>Leo</item>
    </string-array>
</resources>

ArrayAdapter provides us the createFromResource() method which gives us an instance of the ArrayAdapter from the string array we provided.

After that:

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

This method allows us specify the layout the adapter will use to display the list of spinner choices. We use the one provided by the Android Platform.

Finally we set the adapter:

spinner.setAdapter(adapter);

Comments