Android Spinner Tutorial - Drop Down Menu

Spinner component is a set of data options that have been set and provides a standard drop-down menu interface for users to choose an option. In Android we have 2 display modes, one is dropdown and other is Dialog. The default display mode of spinner in android is Drop-Down. 

Generally while using Spinner in android will use below components

  • Spinner
  • Spinner Adapter
  • AdapterView.OnItemSelectedListener

 

Spinner : Android spinner is widget view, which is similar to dropdown list and is used to select one option from the list of options.

Spinner Adapter: Adapter (adapter) is the bridge between View and data. Spinner usually uses ArrayAdapter to display array (Array) data according to the specified layout. SpinnerAdapter defines two views, one is the view of the Spinner itself ( the style after selecting the option); the other is the style of the menu list after the Spinner

AdapterView.OnItemSelectedListener: Set the action after selecting the menu.

 

After setting these three categories, the entire Spinner operation can be completed

Let create a Simple Spinner example

 

Step 1: Add Spinner

Create a new project in Android studio (File->New-> New Project). Select Empty Activity and complete the new project setup.

Add Spinner: Open activity_main.xml file and click [Containers] in Palette, then click [Spinner], right-click, and click [Add to Design] to complete the addition (the default id is spinner).

Now the xml file looks like below

<?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:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">

    <Spinner

        android:id="@+id/spinner"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginStart="32dp"

        android:layout_marginEnd="32dp"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintEnd_toEndOf="parent"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

Step 2: Set Data 

To show data on the spinner we need some data. In this spinner example we are going to show list of widgets to pick one option from the list. So let’s create a data source.

Open string.xml file under resource folder (src/main/res/values/string.xml). Create a String array with the name “widgets_array”

Now the string file look like below

<resources>

    <string name="app_name">CustomSpinner</string>

    <string-array name ="widgets_array">

        <item>TextView</item>

        <item>Button</item>

        <item>Spinner</item>

        <item>Listview</item>

        <item>LinearLayout</item>

 

    </string-array >

</resources>

 

Step 3: Setup the SpinnerAdapter

We have the data source, now we need to set this data to Adapter and add this adapter to the spinner, Now initiate spinner inside our activity file. Here I am showing the code in both java and kotlin.

Kotlin Code

lateinit var spinner:Spinner

spinner=findViewById(R.id.spinner)

 

Java Code

Spinner spinner;

spinner=findViewById(R.id.spinner);

 

Generate ArrayAdapter, set data option string array and layout of default spinner

 

Kotlin Code

val adapter = ArrayAdapter.createFromResource(

    this,  //corresponding Context

    R.array.widgets_array//data option content

    android.R.layout.simple_spinner_item

)

 

Java Code

ArrayAdapter<CharSequence> adapter =

    ArrayAdapter.createFromResource(this, //corresponding Context

        R.array.widgets_array, //data option content

        android.R.layout.simple_spinner_item) ; 

 

 

Specify the style of the option list when the Spinner is expanded. If it is the same as the style when it is not expanded, you can not set

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

 

Now setup spinner with adapter by setAdapter property

 

Kotlin Code

spinner.adapter = adapter

 

Java Code

spinner.setAdapter(adapter);

 

 

Set AdapterView.OnItemSelectedListener

To get the events of the spinner we need to set a Listener to the spinner. We will use OnItemSelectedListener to the spinner to get the selected values form the spinner

 

Kotlin Code

val spnOnItemSelected: AdapterView.OnItemSelectedListener =

    object : AdapterView.OnItemSelectedListener {

        override fun onItemSelected(

            parent: AdapterView<*>?, view: View,

            pos: Int, id: Long

        ) {

            // Action when the option is selected

        }

 

        override fun onNothingSelected(parent: AdapterView<*>?) {

            // Action when nothing is selected

        }

    }

spinner.onItemSelectedListener = spnOnItemSelected

 

Java Code

AdapterView.OnItemSelectedListener spnOnItemSelected

    = new AdapterView.OnItemSelectedListener() {

    public void onItemSelected(AdapterView<?> parent, View view,

                               int pos, long id) {

        // Action when the option is selected

    }

 

    public void onNothingSelected(AdapterView<?> parent) {

        // Action when nothing is selected

    }

};

 

spinner.setOnItemSelectedListener(spnOnItemSelected);

 

After select the option from the spinner it will trigger the onItemSelected method. From here based on the selected position we can get the selected item value.

 

Android Spinner example with Kotlin and Java

 

Android Spinner example with Kotlin and Java 2

Android Interview Questions On Spinner

1. How to set spinner at particular position in android?

A: To set spinner to a particular position we will use setSelection() property to the spinner

spinner.setSelection(2)

 

2. How to get selected value in spinner?

A: To get the selected value of the spinner we will use getSelectedItem() property

spinner.getSelectedItem()//Java

Spinner.spinner.selectedItem //Kotlin

 

3. How to remove selected item from the spinner in Android?

A: To remove the particular item from the spinner we will use the remove() method of the adapter.

adapter.remove(adapter.getItem(pos))

 

Complete Example code for the spinner

Android Spinner Java Code

package com.example.customspinner;

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.Toast;

public class MainActivity2 extends AppCompatActivity {
Spinner spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        spinner=findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter =
            ArrayAdapter.createFromResource(this, //corresponding Context
                R.array.widgets_array, //data option content
                android.R.layout.simple_spinner_item) ; //Default View when the Spinner is not expanded (default and selected styles)

        spinner.setAdapter(adapter);

        spinner.setSelection(2);
         AdapterView.OnItemSelectedListener spnOnItemSelected
            = new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                // Action when the option is selected
                Toast.makeText(getApplicationContext(),"${adapter.getItem(pos)} selected", Toast.LENGTH_SHORT).show();
            }

            public void onNothingSelected(AdapterView<?> parent) {
                // Action when nothing is selected
            }
        };
         spinner.setOnItemSelectedListener(spnOnItemSelected);

    }
}

 

Android Spinner Kotlin Code

package com.example.customspinner

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    lateinit var spinner:Spinner
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        spinner=findViewById(R.id.spinner)

        val adapter = ArrayAdapter.createFromResource(
            this,  //corresponding Context
            R.array.widgets_array,  //data option content
            android.R.layout.simple_spinner_item
        )
        spinner.adapter = adapter
        spinner.setSelection(2)

        val spnOnItemSelected: AdapterView.OnItemSelectedListener =
            object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?, view: View,
                    pos: Int, id: Long
                ) {
                    // Action when the option is selected
               Toast.makeText(applicationContext,"${adapter.getItem(pos)} selected",Toast.LENGTH_LONG).show()
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                    // Action when nothing is selected
                }
            }
        spinner.onItemSelectedListener = spnOnItemSelected
    }
}