How to set an item selected in Spinner in ANDROID?

By | May 10, 2013

This code helps yoy to set an item in your combobox(spinner) in ANDROID.
Here my_spinner is the combobox which we call as spinner in ANDROID.
Declare it in your XML file and link to it by using the following code….
my_spinner= (Spinner)findViewById(R.id.my_spinner);
After that in your code set an item Listener for the spinner using the code below.

my_spinner.setOnItemSelectedListener(spinnerListener);

Now you have registered the listener with the selection event.

Next are the functions that is actually triggered when we select an item in the spinner
“onNothingSelected” function is triggered when nothing is selected.

private Spinner.OnItemSelectedListener spinnerListener
= new Spinner.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
/* This function is called when you select something from the spinner */
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
/**This line sets the index of the spinner.
Here I have given it as position which
can be  any number with in the index range  ***/
my_spinner.setSelection(position);
}};

Please leave your valuable comments.

3 thoughts on “How to set an item selected in Spinner in ANDROID?

  1. Pingback: Customizing a spinner in android.

Leave a Reply

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