Drop-down list (Spinner) in android

If you’re thinking about creating a drop-down list in android, you’ve come to the right place. In this blog post, I will show you how to create a drop-down list in android. I will show you how can you populate the drop-down list with data and how can you handle user selections. So, without further ado, let’s get started!

Actually, I’m using the term drop-down list here, but android doesn’t call it a drop-down list. In the android world, a drop-down list is called a spinner. So, from now on, I will use the term spinner.

How to create a Spinner in android?

I will create a simple app that contains a Spinner and a TextView. The Spinner shows a list of book genres. When I select a genre from the list, it shows the genre in the TextView. First, let’s see the steps, then I will share the full code.

Steps to create the Spinner

Add the spinner to the XML layout using the <Spinner> element.

<Spinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Now, we have to populate the spinner with a list of items. To do this, first I will specify a string array in the string resource file. I will create the choices for the spinner using this array.

<resources>
    <string name="app_name">Spinners_Example</string>
    <string-array name="genres_array">
        <item>Comic</item>
        <item>Romance</item>
        <item>Fairytale</item>
        <item>Fantasy</item>
        <item>Sci-Fi</item>
    </string-array>
</resources>

The spinner takes an ArrayAdapter object as a parameter. You can think of it as a holder of the items for the spinner. Let’s create an ArrayAdapter using the string array that I defined in the string resource file.

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

        // Create an ArrayAdapter for the spinner using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.genres_array, android.R.layout.simple_spinner_item);

        // Provide the layout that should be used when the selection list displays.
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

       // Pass the adapter to the spinner
        spinner.setAdapter(adapter);

Here, I created the ArrayAdpater and passed the adapter to the spinner.

Now, I will set the listener to the spinner so that it will respond when a selection is made. In this case, when a selection is made then the choice appears in the text view.

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                // Retrieve the selected item
                String selectedItem= (String) adapterView.getSelectedItem();
                //show the selected item in the TextView
                textView.setText(selectedItem);
            }

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

            }
        });

That completes the steps. Now, I will share the full code.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/constraint_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="184dp"
        android:layout_height="38dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.189"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.261" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="282dp"
        android:layout_height="52dp"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.496"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/spinner"
        app:layout_constraintVertical_bias="0.202" />
</androidx.constraintlayout.widget.ConstraintLayout>

strings.xml

<resources>
    <string name="app_name">Spinners_Example</string>
    <string-array name="genres_array">
        <item>Comic</item>
        <item>Romance</item>
        <item>Fairytale</item>
        <item>Fantasy</item>
        <item>Sci-Fi</item>
    </string-array>
</resources>

MainActivity.java

package com.example.spinners_example;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

        TextView textView = findViewById(R.id.textView);

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

        // Create an ArrayAdapter for the spinner using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.genres_array, android.R.layout.simple_spinner_item);

        // Provide the layout that should be used when the selection list displays.
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

       // Pass the adapter to the spinner
        spinner.setAdapter(adapter);

        //Set the listener to the spinner
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                // Retrieve the selected item
                String selectedItem= (String) adapterView.getSelectedItem();
                //show the selected item in the TextView
                textView.setText(selectedItem);
            }

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

            }
        });
    }
}

Output:

That completes this post.

Goodbye.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: