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

115 comments on “Android spinner (drop down list) example

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

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

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

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

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

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

    Reply
  7. how to set class path to resources in android studio

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

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

    Reply
  10. 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…

    Reply
  11. Hi , Do you know how to add spinners to spinner?

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

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

    Reply
  13. 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…

    Reply
  14. This is not a dropdown list! Its a popup menu selection!

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

        Reply
  15. 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 ?

    Reply
  16. 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?

    Reply
    1. 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.

      Reply
  17. 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.

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

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

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

      Reply
  18. 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.

    Reply
  19. 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

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

    Reply
  21. 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);
    }
    }
    });

    Reply
  22. 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??

    Reply
  23. how to get the selected spinner string value??

    Reply
  24. dfghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

    Reply
  25. hgjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj

    Reply
  26. 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.

    Reply
  27. 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??

    Reply
  28. Your Majesty, thanks lord for your existence, I was this close to dumping all android world.

    Reply
  29. hey your code is very help full for me n every beginner thanks a lol

    Reply
  30. Hi

    Thank you for this tutorial on creating Android Spinners. I have an Android Spinner View board on Verious with this post. I’d like to share it with anyone interested in creating a Drop Down List. Please let me know if there’s anything I can add to make a more comprehensive resource for other developers.
    http://www.verious.com/board/Giancarlo-Leonio/creating-an-android-spinner-view-from-developers-like-mkyong-and-sai-geetha

    @Veriously

    Reply
  31. Hey,
    M completely new to android!
    Please bare with me for asking such a silly question!
    Where is the “@array/country_arrays” placed??
    in which folder am i supposed to write this file??

    Reply
    1. you should place it under values/strings folder.He has mentioned it up there.

      Reply
  32. I wish you had actually filled spinner 2 from an XML file. I cannot find how to parse and get my data out of an XML file into an Array to load the spinner.

    Reply
  33. Awesome, Can you do a tutorial on how once someone selects their options it saves it to a file so they can go back and look through them?

    Thanks!!!!

    Reply
  34. hey ur tutorial is excellent & can u tell me how to write for date of birth please

    Reply
  35. very nice and accurate example….thanks a lot………..Great work…

    Reply
  36. hello Sir this is absolutely a good example but am searching when i will select a country then automatically the continents of this state will come in another spinner. can you send some solution to me? then i will be grateful to you.

    Thank you.

    Reply
  37. Thanks for your nice and easy to follow tutorial.
    It took sometime to me because I made the mistake of mispelling “spinner” instead of “Spinner” in the class definition on the XML file.

    From Portugal,
    Júlio

    Reply
  38. If the spinner has an array with cities and each city has its own respective url, how do I pass the value from the spinner to run its respective url in a webview?

    Reply
  39. Thanks – helped me solve a problem I’ve been struggling with for hours!

    Reply
  40. Dear Mkyong,

    many THX for this Example!

    But i`m very, very new in Android-/Eclipse-Programming and have one big spinner-problem, that i could´nt solve alone. 🙁
    Downloading the sample, every works fine! But when i try it with a new project on my machine (Mac + Win7), i wont get a DropDown-Button only a square that is cutted diagonal.
    The entries are not shown in a other “window” with option buttons, they will be listed UNDER the spinner.
    The Graghical Design is shown in WHITE.

    I think, it is a problem of my settings, but i have no idea!

    YOU? 😉 (i´m despairing)

    Reply
    1. sorry, me forget. 🙂

      Me use Android 4.1 and Eclipse 4.2.0

      (terrible english…)

      Reply
  41. On the line with:

    btnSubmit.setOnClickListener(new OnClickListener() {

    I get this error message in Eclipse:

    The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new DialogInterface.OnClickListener(){})

    what went wrong?

    Reply
    1. it’s common mistake

      btnSubmit.setOnClickListener(new OnClickListener()

      -> btnSubmit.setOnClickListener(new View.OnClickListener()

      you shoud add View class

      Reply
  42. I want to know how i could implement when select a item in spinner and i clicked the submit button then how could i execute an xml file corresponding to the selected item
    can any one help me……. Thanks in advance

    Reply
  43. Hi Dear:
    i want to develop an Android application showing 5 markers/points in google maps. Is there anybody who already has done this task and know about how it will be accomplished.
    Please reply as soon as possible if any body know. Thanks.

    Reply
  44. Hello dear i am trying to develop Landrule game….for learning purpose.

    I need help to complete my this learning program.

    I would like to ask you how to program:

    after clicking on New Local Game, how to display

    Maps:…….(list of maps)

    # Humans:……..(list of counting)

    # AI……………..(List of counting)

    Difficulty:………..(Easy, Harder)

    Assigning Colors to Each Player:…

    Please Help me so that i can proceed my task to next level, Please it is urgent

    Reply
  45. Thank you very much! I didn’t know the correct approach was to use android layouts for the dropdown and dropdownitem unstead of custom made (which i had trouble coding).

    Reply
  46. in this app use this line facing error remove this line working perfect api level is 8

    android:prompt=”@string/country_prompt”

    Reply
  47. Hi Every one….
    I want to develop LandRule game. in which i want to use Map editing Functionality.
    I need your guidance if you wanted..
    I think you are an experienced and talented person and can guide me in a better way.

    Reply
  48. Hi,
    Thanks for the tutorial,

    Hey in my one application, i need to listen for sound, if sound is of “clap” then i want my android phone to start playing particular song.

    Can you help me with this, how can achieve this, how can i compare that the sound is of “clap”.

    any inputs/points will be helpful.

    Reply
  49. can the same code when implemented with php files be used for adding the contents of spinner to mysql databse?

    Reply
  50. great job, but i wanna try making 2 spinner from database, and i not found good tutorial as yours, i thinks i need yours help this time…thanks before

    Reply
  51. Not many examples on the internet have example with multiple spinners in one activity. Thanks!

    Reply
  52. Thanks for writing this example. It was very helpful. I hardly found any help with multiple spinners tutorial.

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *