Wednesday, 18 March 2015

How to implement spinner in Android ?

The SpinnerView displays one item at a time from a list and enables users to choose among them.
The following Example shows how you can use the SpinnerView in your activity.

Using the SpinnerView to Display an item at a Time 

1 . Using Eclipse, create an Android project and name it as SpinnerView.

2 . Modify the main.xml file located in the res/layout folder as shown here: 

<?xml​ version=”1.0”​encoding=”utf-8”?>
​​​​android:layout_width=”fill_parent” ​​​
​android:layout_height=”fill_parent” ​​​​>

<Spinner ​​​​android:id=”@+id/spinner1” ​
​​​​android:layout_height=”wrap_content” ​​​
​android:drawSelectorOnTop=”true” />


3 . Add the following lines in bold to the strings.xml file located in the res/values folder: 

<?xml ​version=”1.0”​encoding=”utf-8”?>
<string​name=”hello”>Hello​World,​MainActivity!</string> ​
<string-array name=”presidents_array”> ​​
<item>Dwight D. Eisenhower</item> ​
​​​​​​​<item>John F. Kennedy</item> ​
​​​​​​​<item>Lyndon B. Johnson</item>
​​​​​​​​<item>Richard Nixon</item> ​
​​​​​​​<item>Gerald Ford</item> ​​
​​​​​​<item>Jimmy Carter</item>
​​​​​​​​<item>Ronald Reagan</item> ​​
​​​​​​<item>George H. W. Bush</item> ​​
​​​​​​<item>Bill Clinton</item>
​​​​​​​​<item>George W. Bush</item> ​​
​​​​​​<item>Barack Obama</item> ​​​



4 . Add the following statements in bold to the file:

package com.emergingandroidtech.SpinnerView;

import android.os.Bundle;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {
    String[] presidents;   
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        presidents =
        Spinner s1 = (Spinner) findViewById(;
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_dropdown_item, presidents);

        s1.setOnItemSelectedListener(new OnItemSelectedListener()
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
                int index = arg0.getSelectedItemPosition();
                    "You have selected item : " + presidents[index],

            public void onNothingSelected(AdapterView<?> arg0) {}

5 .Click on the SpinnerView and you will see a pop-up displaying the list of presidents’ names. Clicking on an item will display a message showing you the item selected.

No comments:

Post a Comment