Now ,Its time to know spinner in android .Lets start How spinner works and how to work with spinner.
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
Hi..thanks for tutorial.How will you display this in webview? for eg: comparing the two spinners and opening in webview with different links?
ReplyDeleteVery Nice tutorial you can also check this one http://pavanhd.blogspot.in/2013/04/android-spinner-example.html
ReplyDelete