The Wayback Machine - https://web.archive.org/web/20240708101240/https://www.geeksforgeeks.org/spinner-in-android-using-java-with-example/
Open In App

Spinner in Android with Example

Last Updated : 17 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 attributes Description
android:id Used to specify the id of the view.
android:textAlignment Used to the text alignment in the dropdown list.
android:background Used to set the background of the view.
android:padding Used to set the padding of the view.
android:visibility Used to set the visibility of the view.
android:gravity Used 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



Previous Article
Next Article

Similar Reads

How to add Custom Spinner in android?
Spinner is a widget that is used to select an item from a list of items. When the user tap on a spinner a drop-down menu is visible to the user. In this article, we will learn how to add custom spinner in the app. If you want to know more about spinner in detail then click on this link. Approach: Create a new file algorithm_spinner.xml and add the
4 min read
How to Change Spinner Text Style in Android?
A Spinner in Android is a UI element used to display the list of items in a drop-down menu. The spinner is depicted as a downward arrow on the layout. Each of these items is selectable and can be used as user input. In this article, we will show you how to change the Spinner item text styles in Android. More about Spinner in Android can be found at
3 min read
How to Set the Selected Item of Spinner By Value and Not By Position in Android?
Spinner is used in many android applications to display multiple options within a drop-down list and the user will be able to select a specific option from the given list. The default item which is selected within the spinner is the first item within the list which we will be creating to be displayed within the spinner. We can set the specific item
4 min read
Dynamic Spinner in Android
Many times in android applications we have to create any view dynamically without writing any XML code. For that, we can create our view using our Kotlin or Java file. In this article, we will take a look at How to Dynamically create a spinner in an android application. A sample video is given below to get an idea about what we are going to do in t
6 min read
How to Implement Android SearchView with Example
SearchView widget is used to provide a search interface to the user so that the user can enter his search query and submit a request to the search provider and get a list of query suggestions or results. Class Syntax:public class SearchView extends LinearLayout implements CollapsibleActionViewClass Hierarchy:java.lang.Object ↳ android.view.View ↳ a
5 min read
RecyclerView using ListView in Android With Example
RecyclerView is more flexible and advanced version of ListView and GridView. RecyclerView is used for providing a limited window to a large data set, which means it is used to display a large amount of data that can be scrolled very efficiently by maintaining a limited number of Views. In RecyclerView we supply data and define how each item looks,
6 min read
ImageView in Android with Example
ImageView class is used to display any kind of image resource in the android application either it can be android.graphics.Bitmap or android.graphics.drawable.Drawable (it is a general abstraction for anything that can be drawn in Android). ImageView class or android.widget.ImageView inherits the android.view.View class which is the subclass of Kot
4 min read
PhotoView in Android with Example
In this article, PhotoView is added to android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifying the application when the user taps on the photo or when the displayed matrix gets changed. It provides smooth scroll
2 min read
LineAnimationView in Android with Example
LineAnimationView is an animation library that helps to gain the attention of the user. It is useful for creating very beautiful animation. In this animation, an object emerges from the bottom and goes to the top. Some useful features and application of LineAnimationView are: Use this view where if you want the user to wait for some time. ProgressB
3 min read
CountDownTimer in Android with Example
The countdown timer app is about setting a time that moves in reverse order as it shows the time left in the upcoming event. A countdown timer is an accurate timer that can be used for a website or blog to display the countdown to any special event, such as a birthday or anniversary. Likewise, here let's create an Android App to learn how to create
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg