Home > Java > javaTutorial > body text

How to Preselect an Item in a Spinner Based on Value in Android?

Linda Hamilton
Release: 2024-10-30 21:51:02
Original
1012 people have browsed it

How to Preselect an Item in a Spinner Based on Value in Android?

Preselecting an Item in Spinner Based on Value

When updating a view, it's often necessary to preselect a value stored in a database for a Spinner control. The default approach using the Adapter's indexOf method is limited.

Instead, you can achieve this preselection by comparing the target value to the Spinner's items using an ArrayAdapter. Here's an example:

<code class="java">public void setSpinner(String 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);

    if (value != null) {
        int spinnerPosition = adapter.getPosition(value);
        getSpinnerField().setSelection(spinnerPosition);
    }
}</code>
Copy after login

In this code:

  • We create an ArrayAdapter using an appropriate resource file and style.
  • We check if the target value is not null.
  • If the value is valid, we find its position in the adapter using getPosition.
  • Finally, we set the Spinner's selection to the found position.

This approach allows you to preselect an item in a Spinner based on the stored value, not by its position. It's a clean and efficient solution for updating views with specific data.

The above is the detailed content of How to Preselect an Item in a Spinner Based on Value in Android?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!