Android 中列表视图中仅突出显示所选项目

问题描述 投票:0回答:4

我有一个列表视图

contactslist
。我编写了用于突出显示
ListView
中所选项目的代码。它正在发挥作用。当我单击一个项目时,它会突出显示该项目,但问题是如果我单击另一项目,它也会突出显示该项目。我只想突出显示所选项目。当我单击另一个项目时,之前的选择应该消失。

arg1.setBackgroundResource(R.drawable.highlighter);

这是点击监听器中用于突出显示所选项目的代码。我该如何解决这个问题?

我正在设置适配器中行的背景:

public int[] colors = new int[]{0xFFedf5ff, 0xFFFFFFFF}; 
public int colorPos; 

[...]
colorPos = position % colors.length; 
row.setBackgroundColor(colors[colorPos]);
android listview selecteditem
4个回答
126
投票

ListViews
默认情况下没有
choiceMode
设置(它设置为
none
),因此当前选择不会以视觉方式指示。

要更改此设置,您只需将

choiceMode
ListView
属性设置为
singleChoice

如果您想为列表中的所选项目自定义背景,还应该设置
listSelector
属性。在那里您不仅可以指定颜色,还可以指定可绘制对象(图像、图层/状态可绘制对象)。

<ListView android:id="@+id/my_list"
          android:choiceMode="singleChoice" 
          android:listSelector="@android:color/darker_gray" />

如果您不直接使用

ListView
,而是使用
ListActivity
,则需要从代码中设置这些属性,因此您应该使用以下行扩展 Activity 的
onCreate
方法:

getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setSelector(android.R.color.darker_gray);

因此,如果您使用点击侦听器来更改所选行的背景,请从代码中删除它,并使用上面的正确方法。

回复更新

如果您通过 getView 方法设置背景,则不要使用静态颜色,而是将可绘制的状态列表应用于行背景,并将重复父状态设置为 true。这样它将根据项目的当前状态更改其显示:正常、聚焦、按下等。


30
投票

在listview xml中添加“singleChoice”模式

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:choiceMode="singleChoice"
    (...) >
</ListView>

在列表项布局中添加

android:background="?android:attr/activatedBackgroundIndicator

示例

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:orientation="horizontal"
   android:background="?android:attr/activatedBackgroundIndicator">

     <!-- your item content-->

</LinearLayout> 

8
投票

更好的方法是 在你的主题中, @drawable/list_selector

list_selector.xml:

<!-- <item android:drawable="@color/android:transparent"  android:state_selected="true" /> -->
<item android:drawable="@color/list_bg" android:state_selected="true"/>
<item android:drawable="@color/list_bg" android:state_activated="true"/>
<item android:drawable="@color/transparent"/>

然后为 list_row.xml android:background="?android:attr/activatedBackgroundIndicator" 的根设置背景


0
投票

试试这个

onListItemClick

view.getFocusables(POSITION);
view.setSelected(true);

它会突出显示所选内容。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.