Main navigation

Android Spinner Tutorial

adsense

Let’s start coding our Android Spinner Tutorial:

Creating a New Project

  1. Go to File → New → New Project and enter your Application Name (We have named as Android Spinner Tutorial).
  2. Enter Company Domain, this is used to uniquely identify your App’s package worldwide.
  3. Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code Ourselves. Then Click on Next.
  4. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish. We have left Activity Name as MainActivity.
  5. Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps. Make sure build.grade has following code specially compile ‘com.android.support:appcompat-v7:23.1.1’:

Layout of Android Spinner Tutorial

Since we are making two menus, out of which first will be copied from strings.xml so make following changes:

strings.xml

<resources>
    <string name="app_name">Android Spinner</string>
    <string name="action_settings">Settings</string>

    <string name="class_prompt">Choose a Class</string>

    <string-array name="student_class">
        <item>First</item>
        <item>Second</item>
        <item>Third</item>
        <item>Fourth</item>
        <item>Fifth</item>
        <item>Sixth</item>
        <item>Seventh</item>
    </string-array>
</resources>

Now we have to make two android spinners in layout to show two drop down menus in android. We will name them as Spinner1 and Spinner2. Also there will be a button for submit. On clicking this button, a Toast will appear showing the items selecting from android menu.

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical" >

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown"
        android:entries="@array/student_class"
        android:prompt="@string/class_prompt" />

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="match_parent"
        android:spinnerMode="dialog"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" />

</LinearLayout>

Above code is pretty much self explanatory. Now let’s start making the most important part i.e. MainActivity.

Creating Android Adapter

To fill items in android spinner with a list of choices, we need to create a SpinnerAdapter in MainActivity. A SpinnerAdapter is an extended Adapter that is the bridge between a Spinner and its data. Since choices are already pre-determined for first menu, so we will just give its reference from strings.xml as done in following code:

spinner1 = (Spinner) findViewById(R.id.spinner1);  
// When we select this spinner item, a Toast message will be displayed                       
spinner1.setOnItemSelectedListener(this); 
                                                 

When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event. To define the selection event handler for a spinner, we have implemented the AdapterView.OnItemSelectedListener interface and the corresponding onItemSelected() callback method. In the above code of android spinner tutorial, spinner1.setOnItemSelectedListener will execute method onItemSelected whenever an item is selected from spinner1 menu and a Toast will be displayed. Choices are filled in spinner1 through content_main.xml where we are using android:entries=”@array/student_class”.

Now we will create a second menu where items will be added during in MainActivity itself. For this we will create a separate function named CustomAddValues.

CustomAddValues

 // add items into spinner dynamically                                                        
 public void CustomAddValues() {                                                              
                                                                                              
     spinner2 = (Spinner) findViewById(R.id.spinner2);                                        
     List<String> list = new ArrayList<String>();                                             
     list.add("Eleven");                                                                      
     list.add("Twelve");                                                                      
     list.add("Thirteen");                                                                    
     list.add("Fourteen");                                                                    
     list.add("Fifteen");                                                                     
     ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,                        
             android.R.layout.simple_spinner_item, list);                                     
     dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);      
     spinner2.setAdapter(dataAdapter);                                                        
 }                                                                                            

As you could see in above code, we are filling items in drop down menu android through ArrayList created dynamically. After this array is used as list to fill data in drop down menu android. The createFromResource() method allows you to create an ArrayAdapter from the string array. The third argument for this method is a layout resource that defines how the selected choice appears in the spinner control. In our case it is array list. The simple_spinner_item layout is provided by the platform and is the default layout you should use unless you’d like to define your own layout for the spinner’s appearance.

We called setDropDownViewResource(int) to specify the layout the adapter should use to display the list of spinner choices (simple_spinner_dropdown_item is another standard layout defined by the platform).

Call setAdapter() to apply the adapter to your Spinner .

Submitting User Choices

On submitting choices from first and second menu, a Toast message will be displayed showing both choices from both menus. This will be covered under function addListenerOnButton().

// get the selected dropdown list value                                                     
public void addListenerOnButton() {                                                         
                                                                                            
    spinner1 = (Spinner) findViewById(R.id.spinner1);                                       
    spinner2 = (Spinner) findViewById(R.id.spinner2);                                       
    btnSubmit = (Button) findViewById(R.id.btnSubmit);                                      
                                                                                            
    btnSubmit.setOnClickListener(new OnClickListener() {                                    
                                                                                            
        @Override                                                                           
        public void onClick(View v) {                                                       
                                                                                            
            Toast.makeText(MainActivity.this,                                               
                    "OnClickListener : " +                                                  
                            "\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +  
                            "\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),   
                    Toast.LENGTH_SHORT).show();                                             
        }                                                                                   
                                                                                            
    });                                                                                     
}                                                                                           

So we have discussed code of MainActivity.java in parts. You can refer below for full code of MainActivity.java:

MainActivity.java

package com.androidtutorialpoint.androidspinner;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity  implements AdapterView.OnItemSelectedListener {

    private Spinner spinner1, spinner2;
    private Button btnSubmit;

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

        // When we select this spinner item, a Toast message will be displayed
        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner1.setOnItemSelectedListener(this);

        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.student_class, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        spinner1.setAdapter(adapter);


        CustomAddValues();
        addListenerOnButton();

    }

    // add items into spinner dynamically
    public void CustomAddValues() {

        spinner2 = (Spinner) findViewById(R.id.spinner2);
        List<String> list = new ArrayList<String>();
        list.add("Eleven");
        list.add("Twelve");
        list.add("Thirteen");
        list.add("Fourteen");
        list.add("Fifteen");
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(dataAdapter);
    }

    // get the selected dropdown list value
    public void addListenerOnButton() {

        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner2 = (Spinner) findViewById(R.id.spinner2);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);

        btnSubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Toast.makeText(MainActivity.this,
                        "OnClickListener : " +
                                "\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
                                "\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
                        Toast.LENGTH_SHORT).show();
            }

        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Toast.makeText(parent.getContext(),
                "OnItemSelectedListener : " + parent.getItemAtPosition(position).toString(),
                Toast.LENGTH_SHORT).show();
    }

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

    }
}

Now run this code. You will be able to see following screen:

Android Spinner Tutorial

Select the options and Submit. A Toast message will be displayed as shown below:

Android Spinner Tutorial

So our code of Android Spinner Tutorial is complete. You can see demo of this tutorial in the video given at the start of tutorial.



What’s Next ??

You can see our other tutorials on material design like Android ScrollView, ViewPager, Expandablelistview and GridView Tutorials etc.

We hope you liked our Android Spinner Tutorial, please leave comments in the comment section below in the case of any doubts. Let us know how do you liked this Android Spinner Tutorial.

To download the full code for the Android Spinner Tutorial, Click on the Download Now link below.

Android Spinner Tutorial



Reader Interactions

Comments

  1. Very nicce post. I jսst stumbled upοn уouг blog and wished to say that I’ve reaqlly enjoyed surfing аround your blog posts.
    In аny case I’ll bee subscribing to your feed and ӏ hope you write agaiun verʏ soon!

Trackbacks

Leave a Reply

Advertisment ad adsense adlogger