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

About the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
Kevin
Guest
Kevin

Android is constantly evolving – both the SDK and the IDEs. Anytime putting “should be self explanatory” usually means the author doesn’t understand the main concepts or at least not well enough to explain any specifics or nuances. Which versions were you building to in the SDK? How did you generate the CustomOnItemSelectedListener.java?

Mushfiq
Guest
Mushfiq

Very Nice tutorial! Loved it. Make tutorial about all android resources.

killer_darkz
Guest
killer_darkz

thanks for the post.. I really appreciate the job you have done.. thanks man!!! :-)

Joshua
Guest
Joshua

Very helpful and easy to understand. Keep it up!

moein
Guest
moein

Hi. Thank you.

Adidamu Bhavyasri
Guest
Adidamu Bhavyasri

how to set class path to resources in android studio

Farras Doko
Guest
Farras Doko

Anyone, Help me. Why ‘prompt’ in my spinner is “useless”

Mick Dawdy
Guest
Mick Dawdy

This is an awesome tutorial/example. Now i can get this part of my project working. Thank you.

ajijulla sahib
Guest
ajijulla sahib

how to start another activity when click on item from spinner items Please provide a
sample code

Seow Kelvin
Guest
Seow Kelvin

Hi, how do i display the spinner from Parse database? Am a student doing a FYP but i have no idea how to display the spinner retrieving data from parse database…

Mathura Shreedher
Guest
Mathura Shreedher

Hi , Do you know how to add spinners to spinner?

Hemal Adani
Guest
Hemal Adani

Prompt works with Dialog type spinner. Do you have solution for Dropdown spinner? Can we set default text in that?

Mathavan
Guest
Mathavan

hi,let me consider my situation. if i selected a country for example “France”, and then submit, i need to call another function with the parameter of country identity. please explain how can i solve…

Vinod Jaiswal
Guest
Vinod Jaiswal

Thank you buddy!
You rock!

sala
Guest
sala

Hi, after clickin’ submit it bugs :(

Rakhi Dhavale
Guest
Rakhi Dhavale

Thanks for providing this example!

Mark Anthony Laureta
Guest
Mark Anthony Laureta

This is not a dropdown list! Its a popup menu selection!

Adiyat Mubarak
Guest
Adiyat Mubarak

if you want a dropdown list, change the xml spinner style into dropdown.

Mark Anthony Laureta
Guest
Mark Anthony Laureta

No, I don’t want. I just commented here because he’s leading the people in the wrong terminology.

nilesh
Guest
nilesh
Gurinder
Guest
Gurinder

You’re right! Got another tutorial with an actual dropdown LIST

http://www.ahotbrew.com/android-dropdown-spinner-example/

Fulgencio
Guest
Fulgencio

We have tried to run the codes above but we have taken an error which indicates that ” R cannot resolved” .How can we fix it ?

Indy
Guest
Indy

Great tutorial, helped alot

ife
Guest
ife

Thanks, it was really helpful

hn
Guest
hn

hello this is demo

Giuseppe Santoro
Guest
Giuseppe Santoro

Really thank you. This post solved my today-problem!

trackback
Android Dropdown List’i Statik ve Dinamik Olarak Doldurma | Siber G├╝venlik
Fakiraddi
Guest
Fakiraddi

Thanks admin this tutorial helped me alot… thankssss

Fakiraddi
Guest
Fakiraddi

thanks admin it helps alot …nice tutorial

Ricardo
Guest
Ricardo

Thanks for the source

angelo
Guest
angelo

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

cviguy
Guest
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
Guest
cviguy

I got the error resolved.

dev
Guest
dev

how

Pats
Guest
Pats

I get the same error too…Can you please tell me how you resolved it??? Thx

Gurinder
Guest
Gurinder

It’s a little late, but make sure the file CustomOnItemSelectedListener.java exists in com.mkyong.android folder.

othman Da
Guest
othman Da

this is a common problem you need just to import android.widget.AdapterView.OnItemSelectedListener;

absfrm
Guest
absfrm

Really nice and clean tutorial.
thank you

Vitor Vieira
Guest
Vitor Vieira

Muito Obrigado, Foi de grande ajuda!

Thanks a lot, helpfull!