Byron Kiourtzoglou

About Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Android Spinner (Drop Down List) Example

In Android it’s very easy to create Drop Down Lists using the Spinner component. In this tutorial we are going to see how to set up and display a Spinner. There are two ways you can populate the Drop Down List with options. The first way is by creating a hard coded string-array resource in xml form. The second way is to create the options in the drop down list dynamically in run time using an Adapter. We are going to demonstrate both ways.
 
 
 
 
 
 
For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SKD 4.2

1. Create a new Android Project

Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project. You have to specify the Application Name, the Project Name and the Package Name in the appropriate text fields and then click Next.

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

Select “BlankActivity” and click Next.

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created. Then, click Finish.

2. Adding resources

Use the Package Explorer in Eclipse to navigate to res/values/strings.xml

When you open the strings.xml file, Eclipse will display the graphical Resources View editor :

That’s a nice and easy tool you can use to add several resources to your application like strings, integers, color values etc. But we are going to use the traditional way and that is editing the strings.xml file by hand. In the bottom of the screen, press the string.xml tab and paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">AndroidSpinner</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>

    <string name="select">Choose a country</string>
    <string name="select2">Choose an item</string>
    <string name="button_label">Submit</string>

    <string-array name="country_array">
        <item>Greece</item>
        <item>United Kingdom</item>
        <item>Italy</item>
        <item>France</item>
        <item>Germany</item>
        <item>Turkey</item>
        <item>Poland</item>
        <item>India</item>
    </string-array>

</resources>

So, we’ve just created some string resources that we can use in many ways and in many places in our app. We’ve also created a string-array resource. This is a very useful feature when you want to group together a bunch of strings that you intend to use as a list in your application. In our case, we are going to load one of the spinners with this particular array of strings, and it will automatically create the respective options on the drop down list. You don’t need to specify an array/list size nowhere in the code. So when you want to add or remove some options from the drop down list of the spinner, you can just edit the strings.xml file.

3. Creating the two Spinners

Open res/layout/main.xml file :

And paste the following code :

<?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_array"
        android:prompt="@string/select"/>

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/select2" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_label" />

</LinearLayout>

In the code of the first spinner, notice the android:entries="@array/country_array" attribute. This tells the Spinner to use a particular array resource ( in this case the string-array we specified earlier… ) in order to create the options on the drop down list. As you can see there is no such attribute in the code of the second Spinner, because we want to inflate this spinner with options dynamically in run time. You may also notice the android:prompt attribute. This is a label that will be displayed ( as a header… ) when the drop down list shows up.

4. Change the default AppTheme

This step is optional, but in my system with the default theme, the Spinner didn’t work properly. And to be more specific, the prompt header that was supposed to show up when the drop down list was displayed, didn’t. So, if you face the same problem or if the Spinners don’t seem to work as they were supposed to, go to res/values/styles.xml file:

And paste the following code:

<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="android:Theme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

</resources>

Now you can go back to the main.xml and into the Graphical Layout editor, to preview the User Interface you created:

5. Coding

Go to the java file that contains the code of the activity you’ve just created and paste the following code:

package com.javacodegeeks.android.androidspinnerexample;

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 MainActivity extends Activity {

  private Spinner spinner1, spinner2;
  private Button button;

  @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 list = new ArrayList();
	list.add("Item 1");
	list.add("Item 2");
	list.add("Item 3");
	list.add("Item 4");
	ArrayAdapter dataAdapter = new ArrayAdapter(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 MyOnItemSelectedListener());
  }

  public void addListenerOnButton() {

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

	button.setOnClickListener(new OnClickListener() {

	  @Override
	  public void onClick(View v) {

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

	});
  }
}

Let’s focus on the addItemsOnSpinner2 method. In this method we attempt to inflate the second Spinner with some options. To do this we create a regular ArrayList and add some strings to it. Now we need to bundle this ArayList with the second Spinner. So we use an ArrayAdapter and we state that it is going to use the items of the ArrayList to populate the drop down list. Now let’s take a closer look at the addListenerOnSpinnerItemSelection.

As you can see we set up an OnItemSelectedListener for the first spinner. This listener monitors the selection of items in the drop down list of the first spinner. We are going to write our own OnItemSelectedListener in another file: Go to the Package explorer and Right Click on the project name. Select New -> Class . Specify the name of the class and deselect the option “public static void main(String[] args)” (if selected…). Because the class we are creating is going to be an  OnItemSelectedListener we need to implement the respective interface. So, click Add.

Then type name of the interface in the search box (as you can see you don’t have to write or remember the full name of the interface). Then click Add and Finish:

As you will notice a new java file will be created :

Open the MyOnItemSelectedListener.java file and paste the following code :

package com.javacodegeeks.android.androidspinnerexample;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;

public class MyOnItemSelectedListener implements OnItemSelectedListener {

	@Override
	public void onItemSelected(AdapterView parent, View view, int pos, long id) {

		Toast.makeText(parent.getContext(), "Selected Country : " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onNothingSelected(AdapterView parent) {

	}
}

Now, when an item of the drop down list is selected the onItemSelected method is executed.

6. Run the application

This is the main screen of our Application :

If you click on the first Spinner the hard coded drop down list comes up:

If you click on the second Spinner the dynamically created list comes up:

Now, when you select an item from the first list :

And when you press the button:

Download Eclipse Project

This was an Android Spinner (Drop Down List) Example. Download the Eclipse Project of this tutorial: AndroidSpinnerExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close