Home > Java > javaTutorial > How to Keep ListView Selected Item Highlighted in Android?

How to Keep ListView Selected Item Highlighted in Android?

Susan Sarandon
Release: 2024-11-07 06:03:03
Original
514 people have browsed it

How to Keep ListView Selected Item Highlighted in Android?

Keeping ListView Selected Item Highlighted in Android

In Android development, it is often desirable to highlight the selected item in a ListView while displaying details of the selected item in a separate ListView. This article addresses a common issue related to this scenario.

Problem:

When a user selects an item in a ListView (lv_cli), the details of the selected client should be displayed in a separate ListView (lv_cli_det). However, upon doing so, the user's selected item in lv_cli loses its highlight.

Solution:

The solution lies in utilizing the android:choiceMode="singleChoice" attribute in the XML layout. This attribute specifies the selection behavior for the ListView, allowing only one item to be selected at a time. The background of the selected item will automatically be highlighted using the android:listSelector="#666666" attribute.

Code:

<ListView
    android:id="@+id/cli_lista"
    android:layout_width="512dp"
    android:layout_height="wrap_content"
    android:fadeScrollbars="false"
    android:choiceMode="singleChoice"
    android:listSelector="@color/my_selector" >
</ListView>
Copy after login

Alternatively, you can set these attributes programmatically using the setSelector() and setChoiceMode() methods of the ListView class.

Using this approach, the selected item in lv_cli will remain highlighted while the details of the selected client are displayed in lv_cli_det.

Important Note:

It is important to avoid managing view backgrounds directly in response to onItemClick events. Since views are temporary objects, this approach can lead to unpredictable behavior when items are scrolled out of view and reused.

The above is the detailed content of How to Keep ListView Selected Item Highlighted 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