Android Spinner – drop down list

This tutorial will give you hands-on experience in using Android Spinner as a drop-down menu, passing data using an android bundle, and showing popup notification using an 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 a 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.
Table of Contents
  • 1 Android Spinner
    • 1.1 Android Drop Down List
    • 1.2 Android Spinner Example Project Structure
    • 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 selecting 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

      The 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="https://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>
      
      The 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

      The below image shows the android studio project for spinner example.





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="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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="https://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 the 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.

After an item is selected, the
A toast notification message appears for some time.




After sometime toast notification disappears as shown in the below image. It doesn’t stop us from clicking the next button.
android spinner example
Finally, on the second screen, the selected item from the dropdown list is retrieved using Bundles and displayed in the TextView.
android bundles



Post a Comment

0 Comments