问题描述
我有 1 个列表视图 contactslist
.我编写了用于在 ListView
中突出显示所选项目的代码.这是工作.当我单击 1 个项目时,它会突出显示该项目,但问题是如果我单击其他项目,它也会突出显示该项目.我只想突出显示所选项目.当我单击另一个项目时,先前的选择将不得不消失.
I am having 1 list view contactslist
. I wrote the code for highlighting the selected item in the ListView
. It is working. When I click on 1 item it is highlighting that item but the problem is if I click on other item it is highlighting that too. I want to highlight the selected item only. The previous selection will have to gone when I click on another item.
arg1.setBackgroundResource(R.drawable.highlighter);
这是单击侦听器中用于突出显示所选项目的代码.请帮帮我.
This is the code in the click listener using to highlight the selected item. plz help me.
更新
我正在设置适配器中行的背景:
Update
I'm setting the background of the rows in the adapter:
public int[] colors = new int[]{0xFFedf5ff, 0xFFFFFFFF};
public int colorPos;
[...]
colorPos = position % colors.length;
row.setBackgroundColor(colors[colorPos]);
推荐答案
ListViews
默认没有 choiceMode
设置(它设置为 none
),所以当前的选择不会在视觉上显示出来.
ListViews
by default don't have a choiceMode
set (it's set to none
), so the current selection is not indicated visually.
要更改此设置,您只需将 ListView
的 choiceMode
属性设置为 singleChoice
.
如果您想为列表中的选定项目自定义背景,您还应该设置 listSelector
属性.在那里,您不仅可以指定颜色,还可以指定可绘制对象(图像、图层/状态可绘制对象).
To change this, you just need to set the choiceMode
attribute of your ListView
to singleChoice
.
If you'd like custom background for the selected items in your list, you should also set the listSelector
attribute. There you can specify not only colors, but drawables (images, layer-/state-drawables).
<ListView android:id="@+id/my_list"
android:choiceMode="singleChoice"
android:listSelector="@android:color/darker_gray" />
如果你不直接使用ListView
,而是使用ListActivity
,那么这些属性需要从代码中设置,所以你应该扩展你的Activity的带有这些行的 onCreate
方法:
If you don't use a ListView
directly, but a ListActivity
, then these attributes need to be set from code, so you should extend your activity's onCreate
method with these lines:
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setSelector(android.R.color.darker_gray);
因此,如果您使用点击侦听器更改所选行的背景,请将其从代码中删除,并使用上面的正确方法.
So if you were using a click listener to change the background of the selected row, remove that from your code, and use the proper method from above.
回复更新
如果您从 getView 方法设置背景,而不是使用静态颜色,请将可绘制的状态列表应用于行背景,并将duplicateParentState 设置为 true.这样,它将根据项目的当前状态更改其显示:正常、聚焦、按下等.
If you set the background from your getView method, instead of using a static color, apply a state list drawable to the row background with duplicateParentState set to true. This way it will change its display based on the current state of the item: normal, focused, pressed, etc.
这篇关于在android的listview中突出显示所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!