Android onItemClick listview设置2项的颜色

Android onItemClick listview设置2项的颜色,android,listview,Android,Listview,下面的脚本设置(例如)ListItem位置1的颜色,但它也为数字12(11+1)提供了一个漂亮的灰色。这是安卓系统中的某种缺陷吗 @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { ListView.setSelection(arg2); arg1.setBackgroundColor(Color.LTGRAY); adapter.no

下面的脚本设置(例如)ListItem位置1的颜色,但它也为数字12(11+1)提供了一个漂亮的灰色。这是安卓系统中的某种缺陷吗

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    ListView.setSelection(arg2);
    arg1.setBackgroundColor(Color.LTGRAY);
    adapter.notifyDataSetChanged();
}
@覆盖
公共视图单击(AdapterView arg0、视图arg1、整型arg2、长型arg3){
ListView.setSelection(arg2);
arg1.setBackgroundColor(Color.LTGRAY);
adapter.notifyDataSetChanged();
}

列表视图
回收(重用)视图。因此,您需要将背景颜色与数据关联,而不是与视图关联!然后,在
getView()
中,您有机会根据数据正确设置背景色。。。单元格重复使用导致多个listview行以灰色背景绘制

但是,如果您试图根据选择状态设置背景,请考虑以下技术:

// set single or multi-select on your list (CHOICE_MODE_SINGLE = single row selectable)
// do this in onCreate
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
.
.
.
// in your onItemClick, set the checked state of the item
// you DO NOT need to call notifyDataSetChanged
listView.setItemChecked(position, true);
并且,将listview单元格布局的背景设置为内置选择器或自定义选择器

内置:

android:background="?android:attr/activatedBackgroundIndicator"
自定义:

android:background="@drawable/myListBackground"
drawable/myListBackground.xml:


该键是状态激活条目,在选择/检查项目时使用。您还可以为其他状态指定颜色,上面的示例引用colors.xml表中的颜色


有关这方面的更多详细信息,请查看

您的意思是,第12位的项目也会改变颜色?您试图用此代码实现什么?
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true" android:drawable="@color/lightgray" />
    <item android:drawable="@color/transparent" />
</selector>