Android - Default option in spinner
How can i set a default option in a spinner?
I filled 3 spinners with differents que开发者_C百科rys, and maybe i just want to use 2 of that spinners, not the 3. So always is a value set in the spinner. How can i avoid a value? Cause maybe if a fill an array i can set a default option in position 0, but im filling spinners with querys.
I know spinners are made to have a value, so maybe i could put them a default value so in the onitemclicklistener i can avoid using that spinner with an if (valuespinnerselected = "Default" ) dont to anything
You can configure a label and a value for each index of the Spinner
.
Think that the value -1
is the default value that you want to ignore. That way, i think that this piece of code can help you:
Spinner spinner = (Spinner)findViewById(R.id.spinner);
SpinnerItem item1 = new SpinnerItem();
item1.setText("Default Query");
item1.setValue(-1);
SpinnerItem item2 = new SpinnerItem();
item2.setText("Query1");
item2.setValue(10);
SpinnerItem item3 = new SpinnerItem();
item3.setText("Query 2");
item3.setValue(20);
SpinnerItem[] data = new SpinnerItem[3];
data[0] = item1;
data[1] = item2;
data[2] = item3;
ArrayAdapter<SpinnerItem> adapter = new ArrayAdapter<SpinnerItem>(this, android.R.layout.simple_spinner_item, data);
spinner.setAdapter(adapter);
Where SpinnerItem is the class:
public class SpinnerItem {
String text;
Integer value;
public String getText() {
return text;
}
public void setText(String text){
this.text = text;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value){
this.value = value;
}
public String toString() {
return text;
}
}
After that, you can get the selected item and see his value:
SpinnerItem item = (SpinnerItem) spinner.getSelectedItem();
if(item.getValue() == -1){
//do Something.
}
Hope this helped!
I think easiest would be to put a default item like you mentioned. It could be "Please select".
精彩评论