Setting Spinner's Selection by Value, Not Position
When updating a view and the Spinner's selection must match a value stored in the database, the conventional approach is to locate the corresponding position using an indexOf method on the Adapter. However, this approach encounters a roadblock as the Adapter doesn't provide such a method.
To overcome this challenge, a more suitable approach is to utilize the ArrayAdapter's getPosition method. This method, when paired with a suitable ArrayAdapter, enables the identification of the position associated with a specific value.
Consider a scenario where the Spinner named mSpinner contains a value of "some value". To locate and compare its position, follow these steps:
Create an ArrayAdapter from the resource file R.array.select_state:
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
Set the Spinner's Adapter and DropDownViewResource:
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
Next, if the value to be compared (compareValue) is not null:
if (compareValue != null) {
int spinnerPosition = adapter.getPosition(compareValue);
mSpinner.setSelection(spinnerPosition);
}
By employing this approach, the Spinner's selection can be accurately set based on the value stored in the database, providing a seamless user experience during view updates.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3