Spinner sample program in Android
 


This sample android program shows you how to use Spinner  in Android. In this program a list is shown as a dropdown box. When you click on the list, the selected item is shown on the text view. You can use this ArrayAdapter widget and the Spinner object together with the  onListItemClick() method to determine the selected index and process accordingly.

The ArrayAdapterDemo2.java file is as follows:

package com.javasamples;
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.TextView;

public class ArrayAdapterDemo2 extends Activity implements
		AdapterView.OnItemSelectedListener {
	TextView selection;
	String[] items = { "this", "is", "a", "really", 
			"really2", "really3",
			"really4", "really5", "silly", "list" };

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		selection = (TextView) findViewById(R.id.selection);

		Spinner spin = (Spinner) findViewById(R.id.spinner);
		spin.setOnItemSelectedListener(this);

		ArrayAdapter aa = new ArrayAdapter(
				this,
				android.R.layout.simple_spinner_item, 
				items);

		aa.setDropDownViewResource(
		   android.R.layout.simple_spinner_dropdown_item);
		spin.setAdapter(aa);
	}

	public void onItemSelected(AdapterView<?> parent, View v, int position,
			long id) {
		selection.setText(items[position]);
	}

	public void onNothingSelected(AdapterView<?> parent) {
		selection.setText("");
	}
}//class

The output of this program will be as shown in the android emulator below.

The main.xml file in your res/layout folder is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	android:id="@+id/myLinearLayout"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:orientation="vertical"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<TextView
		android:id="@+id/selection"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:background="#ff0033cc"
		android:textSize="14dip"
		android:textStyle="bold">
	</TextView>
	<Spinner
		android:id="@+id/spinner"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
	</Spinner>
</LinearLayout>
 
 
 
 
 
COPYRIGHT © 2017 java-samples.com. ALL RIGHTS RESERVED.