Android – Spinner example

By -

Today we are going to discuss about implementing Spinner widget. Spinner is a widget similar to a drop-down list for selecting items. In this tutorial,we will create a simple spinner widget that displays a list of days. When one is selected, a toast message will display the selected item. (FYI, I have taken this definition from Android.com)

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
    android:layout_height="fill_parent">

	<Spinner
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:id="@+id/spinner1"
		android:layout_margin="10dp">
	</Spinner>

<RelativeLayout>


SpinnerDemoActivity.java

package com.technotalkative.spinnerdemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class SpinnerDemoActivity extends Activity {
    /** Called when the activity is first created. */
	Spinner spinner1;
	private static final String[] daysArray = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    //    Utils.hideTitleBar(this);
        setContentView(R.layout.main);

        InitialSetUpUI();
    }

	// Method to initialize UI
    public void InitialSetUpUI()
    {
    	spinner1 = (Spinner) findViewById(R.id.spinner1);

    	ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item,daysArray);
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	spinner1.setAdapter(adapter);

    	spinner1.setOnItemSelectedListener(new mySpinnerListener());
    }

    class mySpinnerListener implements Spinner.OnItemSelectedListener
    {
		@Override
		public void onItemSelected(AdapterView parent, View v, int position,
				long id) {
			// TODO Auto-generated method stub
			Toast.makeText(parent.getContext(), &quot;The day is &quot; +
			          parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onNothingSelected(AdapterView parent) {
			// TODO Auto-generated method stub
			// Do nothing.
		}

    }
}

Output:
android spinner example

Paresh Mayani

Paresh Mayani is a lead android developer from India. Currently, He is Sr. Software engineer at InfoStretch Solutions Pvt. Ltd. He has been developing android apps since very 1st version i.e. Android 1.5, he says he has seen days and nights of Android history. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

Loading Facebook Comments ...
Loading Disqus Comments ...