How to set selected item of Spinner by value, not by position?
I have a update view, where I need to preselect the value stored in database for a Spinner.
I was having in mind something like this, but the Adapter
has no indexOf
method, so I am stuck.
void setSpinner(String value)
{
int pos = getSpinnerField().getAdapter().indexOf(value);
getSpinnerField().setSelection(pos);
}
Suppose your Spinner
is named mSpinner
, and it contains as one of its choices: "some value".
To find and compare the position of "some value" in the Spinner use this:
String compareValue = "some value";
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
if (compareValue != null) {
int spinnerPosition = adapter.getPosition(compareValue);
mSpinner.setSelection(spinnerPosition);
}
A simple way to set spinner based on value is
mySpinner.setSelection(getIndex(mySpinner, myValue));
//private method of your class
private int getIndex(Spinner spinner, String myString){
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)){
return i;
}
}
return 0;
}
Way to complex code are already there, this is just much plainer.