Skip to content
Related Articles

Related Articles

Improve Article

Spinner in Android with Example

  • Difficulty Level : Expert
  • Last Updated : 17 Aug, 2021

Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the currently selected value and by using Adapter we can easily bind the items to the spinner objects. Generally, we populate our Spinner control with a list of items by using an ArrayAdapter in our Kotlin file. 

Different Attributes for Spinner Widget

XML attributesDescription
android:idUsed to specify the id of the view.
android:textAlignmentUsed to the text alignment in the dropdown list.
android:backgroundUsed to set the background of the view.
android:paddingUsed to set the padding of the view.
android:visibilityUsed to set the visibility of the view.
android:gravityUsed to specify the gravity of the view like center, top, bottom, etc

Example to demonstrate the Spinner

Here is an example of an Android application that displays the list of courses of GFG. Use ArrayAdapter to store the courses list. Create a single MainActivity that contains the spinner and on clicking any item of spinner Toast with that course name will be shown. 

Creating the activities: There will be one activity and hence one XML file for MainActivity. activity_main.xml: XML file for first activity consists of constraint layout with spinner widget. Below is the code for the XML file for activity:

XML




<?xml version="1.0" encoding="utf-8"?>
<!--Constraint layout which contain Spinner widget-->
 
<android.support.constraint.ConstraintLayout
 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.geeksforgeeks.Spinner.MainActivity">
 
    <!--Spinner widget-->
    <Spinner
        android:id="@+id/coursesspinner"
        android:layout_height="50dp"
        android:layout_width="160dp"
        android:layout_marginEnd="10dp"
        android:layout_marginStart="10dp"   
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
   
</android.support.constraint.ConstraintLayout>

Creating the Java and Kotlin file: There is one activity and hence one Java/Kotlin file for the MainActivity file. Java/Kotlin file for Main Activity, in which Array Adapter is used to bind data to the spinner. We will fill data in the array of strings and bind that data to the spinner. Here is the code:  

Java




import android.support.v7.app.AppCompatActivity;
import android.widget.AdapterView;
import android.view.View;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.os.Bundle;
 
// Main Activity implements Adapter view
public class MainActivity
    extends AppCompatActivity
    implements AdapterView.OnItemSelectedListener {
 
    // create array of Strings
    // and store name of courses
    String[] courses = { "C", "Data structures",
                        "Interview prep", "Algorithms",
                        "DSA with java", "OS" };
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Take the instance of Spinner and
        // apply OnItemSelectedListener on it which
        // tells which item of spinner is clicked
        Spinner spino = findViewById(R.id.coursesspinner);
        spin.setOnItemSelectedListener(this);
 
        // Create the instance of ArrayAdapter
        // having the list of courses
        ArrayAdapter ad
            = new ArrayAdapter(
                this,
                android.R.layout.simple_spinner_item,
                courses);
 
        // set simple layout resource file
        // for each item of spinner
        ad.setDropDownViewResource(
            android.R.layout
                .simple_spinner_dropdown_item);
 
        // Set the ArrayAdapter (ad) data on the
        // Spinner which binds data to spinner
        spino.setAdapter(ad);
    }
 
    // Performing action when ItemSelected
    // from spinner, Overriding onItemSelected method
    @Override
    public void onItemSelected(AdapterView<*> arg0,
                            View arg1,
                            int position,
                            long id)
    {
 
        // make toastof name of course
        // which is selected in spinner
        Toast.makeText(getApplicationContext(),
                    courses[position],
                    Toast.LENGTH_LONG)
            .show();
    }
 
    @Override
    public void onNothingSelected(AdapterView<*> arg0)
    {
        // Auto-generated method stub
    }
}

Kotlin




import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
 
class MainActivity : AppCompatActivity(), OnItemSelectedListener {
    // create array of Strings
    // and store name of courses
    var courses = arrayOf<String?>("C", "Data structures",
            "Interview prep", "Algorithms",
            "DSA with java", "OS")
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // Take the instance of Spinner and
        // apply OnItemSelectedListener on it which
        // tells which item of spinner is clicked
        val spin = findViewById<Spinner>(R.id.coursesspinner)
        spin.onItemSelectedListener = this
 
        // Create the instance of ArrayAdapter
        // having the list of courses
        val ad: ArrayAdapter<*> = ArrayAdapter<Any?>(
                this,
                android.R.layout.simple_spinner_item,
                courses)
 
        // set simple layout resource file
        // for each item of spinner
        ad.setDropDownViewResource(
                android.R.layout.simple_spinner_dropdown_item)
 
        // Set the ArrayAdapter (ad) data on the
        // Spinner which binds data to spinner
        spin.adapter = ad
    }
 
    override fun onItemSelected(parent: AdapterView<*>?,
                                view: View, position: Int,
                                id: Long) {
        // make toastof name of course
        // which is selected in spinner
        Toast.makeText(applicationContext,
                courses[position],
                Toast.LENGTH_LONG)
                .show()
    }
 
    override fun onNothingSelected(parent: AdapterView<*>?) {}
}

Output: 

Spinner in Android with Example

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!



My Personal Notes arrow_drop_up
Recommended Articles
Page :