In this Android Spinner Tutorial, we will learn how to make an Android spinner which will allow us to select an item from a drop down menu in Android. There will be two menus, the first will be filled statically and second dynamically. The first menu will be filled when data is pre-determined in Strings.xml while the second will be filled by creating an array dynamically. On selecting an item from first menu, a toast message will be shown while on selecting second one, there will be no Toast. We will see in Android Spinner Tutorial, why there is no Toast in the second menu.
Let’s start coding our Android Spinner Tutorial:
Creating a New Project
- Go to File → New → New Project and enter your Application Name (We have named as Android Spinner Tutorial).
- Enter Company Domain, this is used to uniquely identify your App’s package worldwide.
- Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code ourselves. Then click on Next.
- Choose an Activity Name. Make sure Generate Layout File check box is selected, otherwise we have to generate it ourselves. Then, click on Finish. We have left Activity Name as
MainActivity
. - Gradle will configure your project and resolve the dependencies, Once it is complete, proceed to the next steps. Make sure
build.grade
has the following code especially compile ‘com.android.support:appcompat-v7:23.1.1’:
Layout of Android Spinner Tutorial
Since we are making two menus, out of which first will be copied from strings.xml so make following changes:
strings.xml
<resources>
<string name="app_name">Android Spinner</string>
<string name="action_settings">Settings</string>
<string name="class_prompt">Choose a Class</string>
<string-array name="student_class">
<item>First</item>
<item>Second</item>
<item>Third</item>
<item>Fourth</item>
<item>Fifth</item>
<item>Sixth</item>
<item>Seventh</item>
</string-array>
</resources>
Now, we have to make two Android spinners in layout to show two drop down menus in Android. We will name them as Spinner1
and Spinner2
. Also, there will be a button for submit. On clicking this button, a Toast
will appear showing the items selecting from Android menu.
content_main.xml
="1.0"="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:spinnerMode="dropdown"
android:entries="@array/student_class"
android:prompt="@string/class_prompt" />
<Spinner
android:id="@+id/spinner2"
android:layout_width="match_parent"
android:spinnerMode="dialog"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
The above code is pretty much self explanatory. Now let’s start making the most important part, i.e., MainActivity
.
Creating Android Adapter
To fill items in Android spinner with a list of choices, we need to create a SpinnerAdapter
in MainActivity
. A SpinnerAdapter
is an extended Adapter
that is the bridge between a Spinner
and its data. Since choices are already pre-determined for the first menu, so we will just give its reference from strings.xml as done in the following code:
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(this);
When the user selects an item from the drop-down, the Spinner
object receives an on-item-selected event. To define the selection event handler for a spinner
, we have implemented the AdapterView.OnItemSelectedListener
interface and the corresponding onItemSelected()
callback method. In the above code of Android spinner tutorial, spinner1.setOnItemSelectedListener
will execute method onItemSelected
whenever an item is selected from spinner1
menu and a Toast
will be displayed. Choices are filled in spinner1
through content_main.xml where we are using android:entries=”@array/student_class”
.
Now, we will create a second menu where items will be added during MainActivity
itself. For this, we will create a separate function named CustomAddValues
.
CustomAddValues
public void CustomAddValues() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("Eleven");
list.add("Twelve");
list.add("Thirteen");
list.add("Fourteen");
list.add("Fifteen");
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);
}
As you could see in the above code, we are filling items in drop down menu Android through ArrayList
created dynamically. After this, array is used as list to fill data in drop down menu Android. The createFromResource()
method allows you to create an ArrayAdapter
from the string
array. The third argument for this method is a layout resource that defines how the selected choice appears in the spinner control. In our case, it is array list. The simple_spinner_item
layout is provided by the platform and is the default layout you should use unless you’d like to define your own layout for the spinner’s appearance.
We called setDropDownViewResource(int)
to specify the layout the adapter should use to display the list of spinner choices (simple_spinner_dropdown_item
is another standard layout defined by the platform).
Call setAdapter()
to apply the adapter to your Spinner.
Submitting User Choices
On submitting choices from the first and second menu, a Toast
message will be displayed showing both choices from both menus. This will be covered under function addListenerOnButton()
.
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(MainActivity.this,
"OnClickListener : " +
"\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
}
So we have discussed code of MainActivity.java in parts. You can refer below for the full code of MainActivity.java:
MainActivity.java
package com.androidtutorialpoint.androidspinner;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements AdapterView.OnItemSelectedListener {
private Spinner spinner1, spinner2;
private Button btnSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.student_class, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
CustomAddValues();
addListenerOnButton();
}
public void CustomAddValues() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("Eleven");
list.add("Twelve");
list.add("Thirteen");
list.add("Fourteen");
list.add("Fifteen");
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 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(MainActivity.this,
"OnClickListener : " +
"\nSpinner 1 : "+
String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+
String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onItemSelected
(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " +
parent.getItemAtPosition(position).toString(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Now run this code. You will be able to see the following screen:
Select the options and Submit. A Toast message will be displayed as shown below:
So our code of Android Spinner Tutorial is complete. You can see a demo of this tutorial in the video given at the start of the tutorial.