Spinner on selection listener : Spinner « UI « Android






Spinner on selection listener

  

package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class Test extends Activity {
  String[] presidents;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    presidents = getResources().getStringArray(R.array.presidents_array);
    Spinner s1 = (Spinner) findViewById(R.id.spinner1);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_spinner_dropdown_item, presidents);

    s1.setAdapter(adapter);
    s1.setOnItemSelectedListener(new OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView<?> arg0, View arg1,
          int arg2, long arg3) {
        int index = arg0.getSelectedItemPosition();
        Toast.makeText(getBaseContext(),
            "You have selected item : " + presidents[index],
            Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onNothingSelected(AdapterView<?> arg0) {
      }
    });
  }
}

//main.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"
    >
    
<Spinner 
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true" />
            
</LinearLayout>

//strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">BasicViews5</string>
    <string-array name="presidents_array">
        <item>Dwight D. Eisenhower</item>
        <item>John F. Kennedy</item>
        <item>Lyndon B. Johnson</item>
        <item>Richard Nixon</item>
        <item>Gerald Ford</item>
        <item>Jimmy Carter</item>
        <item>Ronald Reagan</item>
        <item>George H. W. Bush</item>
        <item>Bill Clinton</item>
        <item>George W. Bush</item>
        <item>Barack Obama</item>
    </string-array>
</resources>

   
    
  








Related examples in the same category

1.Using Spinner
2.Disable and enable Spinner
3.Fill data to Spinner with ArrayAdapter
4.Fill data from arrays.xml to Spinner
5.Fill data from arrays.xml to Spinner and ArrayAdapter
6.Spinner Test
7.Spinner Item Selected Listener