Android spinner (drop down list) example

In Android, you can use “android.widget.Spinner” class to render a dropdown box selection list.

Note
Spinner is a widget similar to a drop-down list for selecting items.

In this tutorial, we show you how to do the following tasks :

  1. Render a Spinner in XML, and load the selection items via XML file also.
  2. Render another Spinner in XML, and load the selection items via code dynamically.
  3. Attach a listener on Spinner, fire when user select a value in Spinner.
  4. Render and attach a listener on a normal button, fire when user click on it, and it will display selected value of Spinner.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. List of Items in Spinner

Open “res/values/strings.xml” file, define the list of items that will display in Spinner (dropdown list).

File : res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="app_name">MyAndroidApp</string>
    <string name="country_prompt">Choose a country</string>
 
    <string-array name="country_arrays">
        <item>Malaysia</item>
        <item>United States</item>
        <item>Indonesia</item>
        <item>France</item>
        <item>Italy</item>
        <item>Singapore</item>
        <item>New Zealand</item>
        <item>India</item>
    </string-array>
 
</resources>

2. Spinner (DropDown List)

Open “res/layout/main.xml” file, add two spinner components and a button.

  1. In “spinner1″, the “android:entries” represents the selection items in spinner.
  2. In “spinner2″, the selection items will be defined in code later.

File : res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://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:entries="@array/country_arrays"
        android:prompt="@string/country_prompt" />
 
    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
 
    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" />
 
</LinearLayout>

3. Code Code

Read the code and also code’s comment, it should be self-explanatory.

File : MyAndroidAppActivity.java

package com.mkyong.android;
 
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
 
public class MyAndroidAppActivity extends Activity {
 
  private Spinner spinner1, spinner2;
  private Button btnSubmit;
 
  @Override
  public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);
 
	addItemsOnSpinner2();
	addListenerOnButton();
	addListenerOnSpinnerItemSelection();
  }
 
  // add items into spinner dynamically
  public void addItemsOnSpinner2() {
 
	spinner2 = (Spinner) findViewById(R.id.spinner2);
	List<String> list = new ArrayList<String>();
	list.add("list 1");
	list.add("list 2");
	list.add("list 3");
	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);
  }
 
  public void addListenerOnSpinnerItemSelection() {
	spinner1 = (Spinner) findViewById(R.id.spinner1);
	spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
  }
 
  // 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(MyAndroidAppActivity.this,
		"OnClickListener : " + 
                "\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) + 
                "\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
			Toast.LENGTH_SHORT).show();
	  }
 
	});
  }
}

File : CustomOnItemSelectedListener.java

package com.mkyong.android;
 
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
 
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
 
  public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
	Toast.makeText(parent.getContext(), 
		"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
		Toast.LENGTH_SHORT).show();
  }
 
  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
	// TODO Auto-generated method stub
  }
 
}

4. Demo

Run the application.

1. Result, two spinners are displayed :

android spinner demo1
android spinner demo2

2. Select “France” from spinner1, item selection listener is fired :

android spinner demo3

3. Select “list2″ from spinner2, and click on the submit button :

android spinner demo4

Download Source Code

References

  1. Android Spinner JavaDoc
  2. Android Spinner Example
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: kangen water()

  • Pingback: alkaline water benefits()

  • Pingback: alkaline()

  • Pingback: water ionizer()

  • Pingback: watch movies online()

  • Pingback: watch tv show episodes()

  • Pingback: Blue Coaster33()

  • Pingback: TextToSpeech! Faça a sua aplicação falar! | Android On Board()

  • Pingback: Android Dropdown List’i Statik ve Dinamik Olarak Doldurma | Siber Güvenlik()

  • Fakiraddi

    Thanks admin this tutorial helped me alot… thankssss

  • Fakiraddi

    thanks admin it helps alot …nice tutorial

  • Ricardo

    Thanks for the source

  • https://www.facebook.com/amatirta.angelo angelo

    thanks man!!!..this is what i really need :D

  • cviguy

    I am starting to learn Android. I get an error trying to use this code, on this line
    spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());

    Error:CustomOnItemSelectedListener cannot be resolved to a type

    The quick fixes suggested by Eclipse dont work. I cant find any way to resolve this thru google search.

    • cviguy

      I got the error resolved.

  • http://webanswer.ir absfrm

    Really nice and clean tutorial.
    thank you

  • Vitor Vieira

    Muito Obrigado, Foi de grande ajuda!

    Thanks a lot, helpfull!

  • César Augusto

    Hi, and thank you a lot for this article, It’s really amazing and helpfull, how is all your website.
    So, I need your help, if is possible.
    I’m a student and newer in Android’s world, can you solve a problem with me?
    I have tryed load a spinner with a previously value selected, but, didn’t work.
    Following my code.

    /*

    This code is a part of the method startListener(), implemented on protected void onCreate(Bundle savedInstanceState)
    */

    OnItemSelectedListener selecaoConta = new OnItemSelectedListener()
    {
    @Override
    public void onItemSelected(AdapterView adaptador,
    View arg1, int arg2, long arg3)
    {
    contaDTO = (Conta_DTO) adaptador
    .getSelectedItem();
    }

    @Override
    public void onNothingSelected(AdapterView arg0)
    {
    // TODO Auto-generated method stub

    }
    };

    spnConta.setOnItemSelectedListener(selecaoConta);

    /*

    After, when user select the option for UPDATE Registry, I call the method for load the Activity, The spinner shoulded come with the third item loaded, but how I sad, this not happen.
    Now, this a a part of the method for LOAD a spinner with a especific value selected.

    */

    contaDTO = lancamentoDTO.getObjConta();
    int codConta = 3;

    spnConta.setSelection(codConta);

    Thank you for some help you can give. All help is welcome.

  • hi-tech

    helpfull

  • Peter

    Thank you for this and the other useful example.
    They are a great help for me.

    One question. Is it possible the height of a spinner reduce.
    I know how to change the text, but is it possible to change the minimum
    height of the box too ?

    Thank you

  • joshua

    Super helpful. Straightfoward with great explanations. Thank you my friend

  • Vinicius

    Gr8, tks 4 share it!

  • http://www.ullim.org Ullim

    thanks, this all I need for my code too

  • sss

    final EditText input = (EditText) findViewById(R.id.textView1);
    Button chkCmd = (Button) findViewById(R.id.button1);
    final ToggleButton passTog = (ToggleButton) findViewById(R.id.toggleButton1);
    TextView display = (TextView) findViewById(R.id.textView1);

    passTog.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    if(passTog.isChecked()){
    input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    }else{
    input.setInputType(InputType.TYPE_CLASS_TEXT);
    }
    }
    });

  • Sakthimuthiah

    Thank you so much.Its simply great

  • http://[email protected] azwa

    Thank you..I’m really looking for this code.. i want to do about ticket time from where to where. when the submit button is clicked the time table will appear..how can i do this??

  • http://playtyping.com wawan123

    thanks, this all I need for my code

  • andro

    exactly what i needed
    thank you SIR

    • Mani

      I have some doupt can u solve.

  • Ahmed Gawad

    Great One , Thank you :)

  • Priyesh

    how to get the selected spinner string value??

  • http://ewwwweweewwww oiiiiiiio

    dfghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

  • http://ewwwweweewwww oiiiiiiio

    hgjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj

  • Pingback: Refreshing ListView row inside adapter with spinner in it : Android Community - For Application Development()

  • http://dimazmarham.blogspot.com dimz

    hi…
    how to intent a class when I select button submit?

  • Larry

    Hi mkyong… good posts as always. Im having a challenge in one of my implementations.
    I have an activity which is populated by an array of dynamically created buttons.
    I need to implement the pull to refresh feature in order to refresh the list of buttons on the activity but what I have so far is not working as expected.
    Examples I have mainly use an array of strings.

  • Mithun

    Hey this works really well for me. Thanks a lot for this…
    Could you also let us know how to create a spinner with multiple selection of objects??

  • fahim

    thanks

  • Pingback: Calling different methods depending on which Spinner item is selected - Android | BlogoSfera()