Python Tutorial

Friday, January 14, 2011

Android spinner example

Android Spinner help user to select an item from desired items. Here i implements OnItemSelectedListener geting the Spinner selected item. I also set Spinner selected item to a text view (code: selection.setText(items[position]);
). I used LinearLayout here, if you need better positioning you can use AbsoluteLayout.


//android_spinner.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/selection" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Spinner android:id="@+id/spinner" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawSelectorOnTop="true" /> </LinearLayout>

//AndroidSpinner.java

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;
import android.widget.AdapterView.OnItemSelectedListener;

public class AndroidSpinner extends Activity implements OnItemSelectedListener {

 TextView selection;
 Spinner spin;
 String[] items = { "bangladesh", "bangla", "bd", "australia", "japan",
   "china", "indiaA", "indiaC" };

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.android_spinner);

  selection = (TextView) findViewById(R.id.selection);

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

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

  spin.setAdapter(aa);
 }

 @Override
 public void onItemSelected(AdapterView<?> parent, View v, int position,
   long id) {
  // TODO Auto-generated method stub
  selection.setText(items[position]);

 }

 @Override
 public void onNothingSelected(AdapterView<?> arg0) {
  // TODO Auto-generated method stub
  selection.setText("");

 }
}

output:



Image not found

3 comments:

  1. Nice Example.

    You can also follow my blogs.

    Thank you.

    ReplyDelete
  2. Thanks for helping me to understand basic concepts. As a beginner in Android programming your post help me a lot.It is really a great work and the way in which u r sharing the knowledge is excellent.Android Training in chennai

    ReplyDelete