Android Spinner – drop down list

Filed Under: Android

This tutorial will give you a hands on experience in using Android Spinner as a drop down menu, passing data using android bundle and showing popup notification using android toast.

We will create an android application that consists of a simple spinner that allows selecting an item from a drop down list. We will display static data in the spinner. Selecting an item from spinner would display a toast message.

To pass data in the form of bundles between activities, we’ll use a button to perform an intent and display the data passed to the next screen.

Android Spinner

Android Spinner is just a drop down list similar to what’s seen in other programming languages such as in HTML pages.

In Android, Spinner is used to select one value from a set of values. In the default state, a spinner shows its currently selected value. Touching the spinner displays a drop down menu with all other available values, from which the user can select a new one.

Android spinner is associated with AdapterView. So we need to set the adapter class with the Spinner.

Android Drop Down List

Following xml file shows the layout of a typical spinner in android which consists of a text label and a spinner element tag.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    
    <!-- Text Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="Category:"
        android:layout_marginBottom="5dp"
    />
    
    <!-- Spinner Element -->
    <Spinner 
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/spinner_title"
    />
</LinearLayout>

Following snippet shows how to use a spinner in the activity class.


Spinner spinner = (Spinner) findViewById(R.id.spinner);

Let’s develop an application where we pass the selected value from the Spinner onto the next screen using Bundles and display a Toast message of the selected value at the same time.

Android Spinner Example Project Structure

Below image shows the android studio project for spinner example.

android spinner example, android drop down list

Let’s start with the layout of the MainActivity class. We just need to add Button to the basic_spinner.xml file.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">


    <LinearLayout
        android:orientation="vertical"
        android:padding="10dip"
        android:id="@+id/linear_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <!-- Text Label -->
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:text="Category:"
            android:layout_marginBottom="5dp"
            />

        <!-- Spinner Element -->
        <Spinner
            android:id="@+id/spinner"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:prompt="@string/spinner_title"
            />
    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="NEXT"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="137dp" />


</RelativeLayout>

The layout of the SecondActivity is as follows:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Empty"
        android:id="@+id/txt_bundle"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="103dp" />
</RelativeLayout>

Here is the Android Manifest file.

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="journaldev.com.spinners" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity"/>
    </application>

</manifest>

The MainActivity and SecondActivity java classes are defined as follows.


package journaldev.com.spinners;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Spinner element
        final Spinner spinner = (Spinner) findViewById(R.id.spinner);
        Button button=(Button)findViewById(R.id.button);

        // Spinner click listener
        spinner.setOnItemSelectedListener(this);

        // Spinner Drop down elements
        List<String> categories = new ArrayList<String>();
        categories.add("Item 1");
        categories.add("Item 2");
        categories.add("Item 3");
        categories.add("Item 4");
        categories.add("Item 5");
        categories.add("Item 6");

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);

        // Drop down layout style - list view with radio button
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        spinner.setAdapter(dataAdapter);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent= new Intent(MainActivity.this,SecondActivity.class);
                intent.putExtra("data",String.valueOf(spinner.getSelectedItem()));
                startActivity(intent);
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // On selecting a spinner item
        String item = parent.getItemAtPosition(position).toString();

        // Showing selected spinner item
        Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();

    }

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

}

package journaldev.com.spinners;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);

        TextView  textView=(TextView) findViewById(R.id.txt_bundle);
        Bundle bundle=getIntent().getExtras();
        String data=bundle.get("data").toString();
        textView.setText(data);
    }
}

In the above code, we’ve displayed a toast when an item from the spinner dropdown menu is selected. On button click we pass the selected spinner item as a string value to the next activity using android bundle. Then the data is retrieved from the bundle and displayed in a TextView. Quick easy and simple, isn’t it?

The screenshots of the app are shown below. I am running it on one of the emulators.

The first screen shows the drop down list contents when the Spinner is opened.

android spinner drop down list

After an item is selected, Toast notification message appears for some time.

android drop down menu

After sometime toast notification disappears as shown in below image. It doesn’t stop us in clicking the next button.

android spinner example

Finally, in the second screen, the selected item from the dropdown list is retrieved using Bundles and displayed in the TextView.

android bundles

Below is a sample run of our android spinner example application in emulator.

android spinner, android drop down list

That’s all for now, we will look into Android ListView in next post. You can download Android Spinner, Bundle and Toast example project from below link.

Reference: Official Doc

Comments

  1. ajinkya jadhav says:

    hi sir i am refereed your code part for my application for reference but i am facing on e problem application closed automatically.
    my code steps is like that
    1) In my main activity i am giving three button for select device like three button on my main activity
    2) If i click on first button then flow goes to this activity correctly next in this activity i am using spinner for select one item from the list. In this activity i am using one button for jump to next activity(second activity to third activity) for perform my final task but if i click on this button then application is closed and main thread error is occurred.

  2. Expert Training Institute says:

    Thanks, for sharing this list with us, I really found this helpful and I also believe that these things gonna help me in future and I hope you will share these kinds of content more often.

  3. Arvind Reddy says:

    Hey this seems to be simple, Suppose I have 2 spinners and I am populating the spinners from JSON file. When I click next, the 2 spinner values go to my web service and retrieve a list. I can populate the spinners but I am having difficulty in getting the list of items. Any help?

    1. Anupam says:

      It’s easier to provide solutions to such questions when the source code is present.

  4. Ankit says:

    if i want to display something else like price etc then what will be the code

  5. Ragu says:

    Babu, I used your code (copy and paste) to create a list-array of all Indian states and it is working good.. Now, when someone selects “Kerela” I wand to show districts of Kerela only to select from in another spinner just below the state spinner. Can you give me rough Idea of how to proceed, I am as new an app developer as I am a coder.

    1. Ragu says:

      Instead of going to next activity, i want to go to next spinner in the same activity and the content of the second spinner should be determined by the item selected in the first spinner.

  6. pradeep m says:

    sir how to filter the colleges on the selection of department and the colleges in spinner

  7. tayyyab khan says:

    sir i am need android language translator source code plzzz its question of my future

    1. Rajendra P Mahato says:

      you can use google traslator api

  8. Nikhil Bhagare says:

    Nice Article. Can please explain some concepts in detail. like how adapter works.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages