How to Create Android Spinner Programmatically and Assign an Event Handler

In this example I will discus on how to create android spinner programmatically.


General Idea:
Get reference to the Spinner
Spinner spinner = (Spinner)findViewById(R.id.spinner_id);
Make an ArrayAdapter
List entries = …; // Can also use String[]
ArrayAdapter spinnerAdapter =
new ArrayAdapter(this, android.R.layout.simple_spinner_item, entries);

Specify the drop down View resource
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Set the adapter for the Spinner
spinner.setAdapter(spinnerAdapter);

XML: Layout File Entry
res/layout/activity_spinner_ex2.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    
    <!-- Text Label -->

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/lblCountry" />

     <!-- Spinner Element -->
    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Note that we do not specify here any android:entries attribute.
Main Activity
SpinnerEx2Activity.java

package com.bar.example.androidspinnerexample;

import java.util.ArrayList;
import java.util.List;

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

public class SpinnerEx2Activity extends Activity {
	Spinner sprCoun;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_spinner_ex2);
		addItemsOnSpinner2();
		sprCoun.setOnItemSelectedListener(new SpinnerHandler(this));
	}

	// add items into spinner dynamically
	public void addItemsOnSpinner2() {

		sprCoun = (Spinner) findViewById(R.id.spinner2);
		List<String> list = new ArrayList<String>();
		list.add("Afghanistan");
		list.add("Bangladesh");
		list.add("Bhutan");
		list.add("India");
		list.add("Maldives");
		list.add("Sri Lanka");
		list.add("Nepal");
		list.add("Pakistan");
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sprCoun.setAdapter(dataAdapter);
	}

	public void showToast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_LONG).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.spinner_ex1, menu);
		return true;
	}

}

Custom Event Handler Class
SpinnerHandler.java

package com.bar.example.androidspinnerexample;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;

public class SpinnerHandler implements OnItemSelectedListener {
	private boolean isFirst = true;
	private SpinnerEx2Activity se2a;
	public SpinnerHandler(SpinnerEx2Activity activity){
		
		this.se2a = activity;
	}
	/** This method will invoke when an entry is selected. Invoked once 
        when Spinner is first displayed, then again for each time the user selects something
         */
	@Override
	public void onItemSelected(AdapterView<?> spinner, View selectedView, 
			int selectedIndex, long id) {
		// Do not want to display the toast while the activity first loaded.
		if (isFirst) {
			isFirst = false;
			} else {
			String selection = 
			spinner.getItemAtPosition(selectedIndex).toString();
			//String message =
			//String.format(mItemSelectedMessageTemplate, selection);
			se2a.showToast("You selected "+selection);
			}
		
	}
	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
	}

Emulator Screenshot:
android_spinner_ex2

You can download all android example from here.

 

admin

Hello! I am Md. Abdul Bari; founder and admin of javaknowledge; currently providing training as a J2EE faculty in The Computers Ltd. Dhaka, Bangladesh under an IT Scholarship project provided by IDB-BISEW. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

More Posts - Website

Follow Me:
TwitterFacebookGoogle Plus

18,305` Total Views

One comment

  • faraaz614@gmail.com

    thanks for sharing this helped alot but still i m geting error at this line
    ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);

    At ………… simple_spinner_item
    where is this i have even downloaded your project
    can u help…

Leave a Reply

Your email address will not be published. Required fields are marked *


+ two = 11