Android Spinner

In Android combo box is called as Spinner. This tutorial shows you, how to use Spinner in your application.

Step 1:
Create an Android project with a project name “Spinner Sample” and a package name “com.javahelps.sample.spinner”.

Step 2:
Modify the activity_main.xml as shown below. Notice that there is a UI component Spinner which is the combo box used to display some names of animals.
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="Select an animal"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Spinner
        android:id="@+id/cmbAnimals"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/txtInfo" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/cmbAnimals">
        <ImageView
            android:id="@+id/imgAnimal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"/>
    </RelativeLayout>

</RelativeLayout>
Step 3:
The images I have used in this project can be downloaded from this link. Download the images and copy them.

Right click on the drawable folder and select “Paste”.


Step 4:
Android Studio will ask you to select the folder to paste. Select the drawable-hdpi folder and click OK.


In the next confirm dialog also just click OK and continue.


Note: Importing images without re-sizing into the project is not recommended. However, in this project the images are directly imported in order to reduce the complexity of this tutorial.

Step 5:
Modify the MainActivity.java according to the following code.
package com.javahelps.sample.spinner;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;


public class MainActivity extends ActionBarActivity {
    // References to GUI components.
    private Spinner cmbAnimals;
    private ImageView imgAnimal;

    // Animal names
    private final String[] animals = {"Deer", "Elephant", "Jaguar", "Lion", "Tiger", "Wolf"};
    // Animal image animalIDs
    // Both names and image animalIDs are in the same order
    private final int[] animalIDs = {R.drawable.img_deer, R.drawable.img_elephant, R.drawable.img_jaguar, R.drawable.img_lion, R.drawable.img_tiger, R.drawable.img_wolf};

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

        // Find the GUI components.
        this.cmbAnimals = (Spinner) findViewById(R.id.cmbAnimals);
        this.imgAnimal = (ImageView) findViewById(R.id.imgAnimal);

        // Create an array adapter and set it to the Spinner.
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, animals);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        this.cmbAnimals.setAdapter(adapter);

        // Set the message to default.
        this.cmbAnimals.setSelection(0);

        // Set itm selected listener.
        this.cmbAnimals.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                imgAnimal.setImageResource(animalIDs[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Do nothing
            }
        });
    }

}
Note that there are two arrays in MainActivity. The String array is used to store the names of animals and the int array is used to store the drawable id of their images. Maintaining same order in both arrays let us to directly map the image of selected animal based on the position selected in the Spinner.

Same as ListView, Spinner also needs an adapter to feed the array or List of items. Spinner needs two layouts for View. “android.R.layout.simple_spinner_item” is used to display the selected item in the Spinner and “android.R.layout.simple_spinner_dropdown_item” is used to display list of items to select one of them.

Step 6:
Now you are ready to run and test the application. Save all the modifications and run the application.

For the completed project, click on this link.

Sample Problem
A partially completed template is provided at this link. Purpose of this application is displaying a welcome message in different languages. If you are not familiar with displaying text with custom font, follow this tutorial first. In the provided template, an activity with a TextView for welcome message and a Spinner with three languages are provided. When user selects a language in the spinner, a welcome message in that language should be displayed. Language related fonts, the welcome messages in those languages and the implementation to display the message are already provided in the template. You are just required to implement the Spinner related code only.


Find the projects at Git Hub.
Previous
Next Post »

Contact Form

Name

Email *

Message *