突出显示android中listview中的选定项目

时间:2011-05-02 05:26:45

标签: android listview selecteditem

我有一个列表视图contactslist。我编写了代码以突出显示ListView中的所选项目。这是工作。当我点击1项时,它突出显示该项目,但问题是如果我点击其他项目也突出显示该项目。我想只突出显示所选项目。当我点击另一个项目时,之前的选择将不复存在。

arg1.setBackgroundResource(R.drawable.highlighter);

这是点击侦听器中用于突出显示所选项目的代码。请帮助我。

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

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

[...]
colorPos = position % colors.length; 
row.setBackgroundColor(colors[colorPos]);

4 个答案:

答案 0 :(得分:112)

默认情况下,

ListViews没有choiceMode设置(设置为none),因此当前选择不会直观显示。

要更改此设置,您只需将choiceMode的{​​{1}}属性设置为ListView即可。
如果您想要列表中所选项目的自定义背景,则还应设置singleChoice属性。在那里,您不仅可以指定颜色,还可以指定绘图(图像,图层/状态绘制)。

listSelector

如果您不直接使用<ListView android:id="@+id/my_list" android:choiceMode="singleChoice" android:listSelector="@android:color/darker_gray" /> ,而是使用ListView,则需要从代码设置这些属性,因此您应该使用这些行扩展活动的ListActivity方法:

onCreate

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

回复更新

如果从getView方法设置背景,而不是使用静态颜色,请将状态列表drawable应用于行背景,并将duplicateParentState设置为true。这样它将根据项目的当前状态更改其显示:正常,聚焦,按下等。

答案 1 :(得分:26)

在listview xml中添加“singleChoice”模式

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

在列表项目布局中添加

  

机器人:背景=“机器人: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> 

答案 2 :(得分:8)

更好的方法是 在你的主题中,  @绘制/ 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的root的背景android:background =“?android:attr / activatedBackgroundIndicator”

答案 3 :(得分:0)

onListItemClick

处尝试此操作
view.getFocusables(POSITION);
view.setSelected(true);

它突出了选择。