In this blog, we will learn what spinner is and how we should implement it for our Android applications. If you want to learn more about its customization check out this Android Custom Spinner article. 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 that can be used to display the multiple options to the user in which the 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.


10 Comments

responder · January 5, 2021 at 1:23 am

Fantastic beаt ! I woᥙld like to apprentice while you amend your
web site, how could i subscribe for a blog site? The account ɑided me a
acceptabⅼe deal. I had been a little bit acqսaintеd
of this your broadcast offered bright cleаr concept

    Subhojit · March 2, 2021 at 10:18 pm

    Sure, the broadcast will be discussed soon!

News XMC.pl · January 28, 2021 at 7:17 am

Aw, this was a really nice post. In idea I would like to put in writing like this additionally – taking time and actual effort to make a very good article but what can I say I procrastinate alot and by no means seem to get something done.

www.Filozofia.XMC.pl · February 18, 2021 at 9:08 am

Ive been meaning to read this and just never got a chance. Its an issue that Im very interested in, I just started reading and Im glad I did. Youre a excellent blogger, 1 of the very best that Ive seen. This weblog unquestionably has some facts on topic that I just wasnt aware of. Thanks for bringing this things to light.

    Subhojit · March 2, 2021 at 10:12 pm

    Nice to hear that! Keep reading…

Kultura USA · February 21, 2021 at 6:31 pm

I ran into this page accidentally, surprisingly, this is a amazing blog :-). The site owner has carried out a superb job of putting it together, the info here is really insightful. You just secured yourself a guarenteed reader.

    Subhojit · March 2, 2021 at 10:11 pm

    Thanks for reading. Hope I will share more interesting topics.

Japonia Tokio · February 25, 2021 at 12:14 pm

Funny I just found your site by searching for Hierchloe oderatus on Google. But I cant find any articles on that topic on here?

Cukrzyca.XMC.pl · February 28, 2021 at 2:06 pm

I’m nonetheless learning from you, as I’m trying to obtain my goals. I definitely liked reading everything which is written on your website.Keep the stories coming. I enjoyed it!

    Subhojit · March 2, 2021 at 10:07 pm

    Hope I will entertain you more.

Leave a Reply

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