Monday, May 27, 2013

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