In this blog, we will learn what spinner is and how we should implement it for our Android applications. At the bottom of this article, you will have a video tutorial though.

Spinner Example

What is Spinner?

Spinner is like a drop-down list which can be used to display the multiple options to the user in which user can select only one option.

In Android, Spinner is associated with AdapterView class (AdapterView is a ViewGroup that displays items loaded into an adapter). Therefore you need to use one of the adapter classes with the spinner such as ArrayAdapter.

Note: In the default state, a spinner shows its currently selected value.


Android Spinner Example

In this example, we are going to display some font sizes, in which user can select a new font size to change our Hello World text’s size. So simple! First of all, we need to add the spinner container from the palette.

Add Spinner from the palette

Following activity.xml file shows the layout of a typical Android Spinner which consists of two TextView tags and a spinner tag.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txt_hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_centerInParent="true"/>

    <TextView
        android:id="@+id/txttitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Change Text Size"
        android:layout_marginStart="30dp"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="30dp"/>

    <Spinner
        android:id="@+id/spinnerTextSize"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txttitle"
        android:layout_marginStart="30dp"
        android:layout_marginEnd="30dp"
        android:layout_marginTop="10dp"/>
    
</RelativeLayout>

Next, we need to refer the spinner by its ID from the MainActivity.java class.

public class MainActivity extends AppCompatActivity {
    private TextView txtHelloWorld;
    private Spinner spinnerTextSize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtHelloWorld = findViewById(R.id.txt_hello_world);
        spinnerTextSize = findViewById(R.id.spinnerTextSize); 
    }
}

Now we need some data that we have to populate in the Spinner Container. And for this project, we will be using String Array resource. Following snippet shows how to use XML resources for an array element.

array.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="font_sizes">
        <item>8</item>
        <item>16</item>
        <item>24</item>
        <item>34</item>
        <item>48</item>
    </string-array>
</resources>

Now we will be using the array name “font_sizes” to access it from MainActivity.java class.

String[] textSizes = getResources().getStringArray(R.array.font_sizes);

We have our list in the textSizes variable. Now we will be creating an adapter and set up the drop-down view resource. And there have two ways to create an adapter.

– Method 1

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, textSizes);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

– Method 2:

ArrayAdapter adapter1 = ArrayAdapter.createFromResource(this, R.array.font_sizes, android.R.layout.simple_spinner_item );
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

simple_spinner_item, simple_spinner_dropdown_item is the default layout resources provided by the Android Framework. Though you can create your own separate layouts.

Now we just have to set the adapter as below snippet.

spinnerTextSize.setAdapter(adapter);



Let’s implement the interface

Finally, we need to add an interface which will be listening for spinner selection changes. So that we can easily update the UI.

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
}

ParametersDescriptions
parentAdapterView: The AdapterView where the click happened.
viewView: The view within the AdapterView that was clicked (this will be a view provided by the adapter)
positionint: The position of the view in the adapter.
idlong: The row id of the item that was clicked.
Brief descriptions about the all arguments of onItemSelected


And also don’t forget to call setOnItemSelectedListener and pass this as the interface instance from the onCreate method otherwise spinner won’t be able to listen for any changes.

    private Spinner spinnerTextSize;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        spinnerTextSize = findViewById(R.id.spinnerTextSize); 
        spinnerTextSize.setOnItemSelectedListener(this);
    }

Last but not the least, from the interface AdapterView.OnItemSelectedListener we got two override methods onItemSelected and OnNothingSelected. OnNothingSelected method will be useful when the user taps on the spinner and selects nothing from there. And if the user selects an item from the spinner then OnItemSelected method will be invoked.



Here is the complete code for MainActivity.java

MainActivity.java

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
    private TextView txtHelloWorld;
    private Spinner spinnerTextSize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtHelloWorld = findViewById(R.id.txt_hello_world);
        spinnerTextSize = findViewById(R.id.spinnerTextSize);

        spinnerTextSize.setOnItemSelectedListener(this);

        String[] textSizes = getResources().getStringArray(R.array.font_sizes);
        ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_spinner_item, textSizes);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerTextSize.setAdapter(adapter);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (parent.getId() == R.id.spinnerTextSize) {
            String valueFromSpinner = parent.getItemAtPosition(position).toString();
            txtHelloWorld.setTextSize(Float.parseFloat(valueFromSpinner));
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
}



Video Tutorial

Drop-down list using Android Spinner.

Complete Practical

Download this project to your local.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *