Appearance
How to set selected item of Spinner by value, not by position?
Android's Spinner natively supports selection only by position using the setSelection(int position) method. To select an item by its value, you must first find the corresponding position in the adapter and then pass that index to setSelection().
Here is an example of how to locate the position of a value and set it as the selected item:
java
Spinner spinner = findViewById(R.id.spinner);
String valueToSelect = "item2"; // value to select
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.items, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
// Find the position of the value
int position = -1;
for (int i = 0; i < adapter.getCount(); i++) {
if (String.valueOf(adapter.getItem(i)).equals(valueToSelect)) {
position = i;
break;
}
}
// Set the selected item by the found position
if (position != -1) {
spinner.setSelection(position);
}In this example, the Spinner is populated with an array of items from the R.array.items resource. We iterate through the adapter to find the index matching valueToSelect, then use setSelection() to apply it.