Spinner in Android using Java with Example

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 currently selected value and by using Adapter we can easily bind the items to spinner object. 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:visibilty 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 single MainActivity which conntains the spinner and on clicking any item of spinner Toast with that course name will be shown.

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

    activity_main.xml

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?xml version="1.0" encoding="utf-8"?>  
    <!--Constraint layout which contain Spinner widget-->
      
    <android.support.constraint.ConstraintLayout 
      
        xmlns:android="http://schemas.android.com/apk/res/android"  
        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>  

    chevron_right

    
    

  • Creating the Java file: There is one activity and hence one Java file for Main Activity. Java 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 code:

    MainActivity.java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    package com.geeksforgeeks.Spinner;
      
    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
        }
    }

    chevron_right

    
    

Output:

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.