Lets start How spinner works in android.

Spinner is widget similar to dropdown list for selecting items.

res->layout->main.xml

 <Spinner android:id="@+id/spinner" android:layout_width="match_parent"
  android:layout_height="wrap_content" />

now open your java class and insert following  code in OnCreate() method.

Spinner  spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, INDIAN_STATE);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter); 

Listining spinner using OnItemSelectedListener.Mind that never use OnItemClickListener for spinner.when you use spinner then set OnItemSelectedListener for get selected item from spinner.

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
      String str =(String)parent.getSelectedItem(); 
}

public void onNothingSelected(AdapterView<?> parent) {

 }
});

You can get Selected value from spinner using getSelectedItem in onItemSelected method.

And onNothingSelected method is called when you choose nothing from spinner.

When you  setOnItemSelectedListener to spinner it called when your Activity start, and its called onItemSelected method.So you can get default selected value from spinner.

Using setSelection(position) method you can set position of spinner.

Now when you working  with more than one spinner and you have one setOnItemSelectedListener for all spinners then get selected value using spinner’s name.


String str1= (String) spinner1.getSelectedItem();
String str2= (String) spinner2.getSelectedItem();

Download Full Source Code From Here

Comments

comments

2 comments

  • FirstEugene
    FirstEugene

    I see you don’t monetize your site, don’t waste your
    traffic, you can earn additional cash every month because you’ve got
    hi quality content. If you want to know how to make extra $$$, search for: Mrdalekjd methods for $$$

  • board
    board

    Very nice article. I certainly appreciate
    this website. Continue the good work!

Leave a Reply

Your email address will not be published. Required fields are marked *
You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Comments

comments