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 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.
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>
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.
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 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, Toast notification message appears for some time. After sometime toast notification disappears as shown in below image. It doesn’t stop us in clicking the next button. Finally, in the second screen, the selected item from the dropdown list is retrieved using Bundles and displayed in the TextView. Below is a sample run of our android spinner example application in emulator. 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.
Download Android Spinner, Bundle and Toast Example Project
Reference: Official Doc
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Sir, I want to set default item to spinner got from getIntent of another activity
- shrutika
The tutorial is quite clear and looks useful. I have been trying to get the source to work but as I AM NOT a GRADLE EXPERT I have failed miserably. I wonder if you could re-examine - rebuild this project with a current version of IDE, GRADLE etc etc . One work around for me would be to take out the .xml and .java files and force them into an empty project in an up-to-date IDE … best regards
- matroxmike
Sir if i take 2 spinner them how can i add onItemSelected method for both spinner ?please reply
- Sitansu
do we have any link/site/place from where I can get pre-defined snipper? I want of Indi’s location.Like State, City, Region, Taluka…
- Adi
You’re awesome! I really appreciate for your code and explain.
- Chang
Thank you. this helped me a lot :)
- Grace
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.
- ajinkya jadhav
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.
- Expert Training Institute
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?
- Arvind Reddy
if i want to display something else like price etc then what will be the code
- Ankit