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

CEO & Co-Founder at SolGuruz® | Organiser @ GDG Ahmedabad | Top 0.1% over StackOverflow | 15+ years experienced Tech Consultant | Helping startups with Custom Software Development

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