Main Tutorials

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 Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
115 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Farras Doko
6 years ago

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

Mushfiq
6 years ago

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

Joshua
6 years ago

Very helpful and easy to understand. Keep it up!

moein
6 years ago

Hi. Thank you.

Seow Kelvin
8 years ago

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…

Kevin
9 years ago

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?

Nicholas
5 years ago
Reply to  Kevin

Well, Kevin. 2019 now and this tutorial sems extremely correct to me. It solved my issues just fine, plain and simple. You should not judge.
And CustomOnItemSelectedListener.java is, as the name says, a custom made class. So it wasn’t self generated, Mkyong must have designed it with this intended purpose.

harris
3 years ago

my spinner is done. how should I write to code the choose from Listbox and display the details in text view

Anas
4 years ago

Hi..
My drop list not including ” import class”
Please advice how can i got it in android studio.
Thanks

itguy041
5 years ago

awesome bro clear cut codes

dwi
5 years ago

Very Thanks to you master, i’m from indonesia,,android dev. beginer

Bashir Manafikhi
5 years ago

Nice

killer_darkz
6 years ago

thanks for the post.. I really appreciate the job you have done.. thanks man!!! 🙂

Adidamu Bhavyasri
8 years ago

how to set class path to resources in android studio

ajijulla sahib
8 years ago

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

Numan Ghani
4 years ago
Reply to  ajijulla sahib

yes i am father of android studio

Mathura Shreedher
8 years ago

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

somedude
4 years ago

Just add to the power of two. You can also use square root for half a spinner.

hoho
4 years ago
Reply to  somedude

It’s so funny that I forgot to laugh

Hemal Adani
9 years ago

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

Mathavan
9 years ago

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
9 years ago

Thank you buddy!
You rock!

sala
9 years ago

Hi, after clickin’ submit it bugs 🙁

Rakhi Dhavale
9 years ago

Thanks for providing this example!

Mark Anthony Laureta
9 years ago

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

Gurinder
8 years ago

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

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

Adiyat Mubarak
9 years ago

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

Mark Anthony Laureta
9 years ago
Reply to  Adiyat Mubarak

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

Fulgencio
9 years ago

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
10 years ago

Great tutorial, helped alot

ife
10 years ago

Thanks, it was really helpful

hn
10 years ago

hello this is demo

Giuseppe Santoro
10 years ago

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

Fakiraddi
10 years ago

Thanks admin this tutorial helped me alot… thankssss

Fakiraddi
10 years ago

thanks admin it helps alot …nice tutorial

Ricardo
10 years ago

Thanks for the source

angelo
10 years ago

thanks man!!!..this is what i really need 😀