@David Wasser是正确的...单元格重用会导致多个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);
而且,设置背景上的列表视图单元布局的内置或自定义选择
内置的
android:background="?android:attr/activatedBackgroundIndicator"
CUSTOM:
android:background="@drawable/myListBackground"
抽拉/ myListBackground.xml:
<?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>
关键是state_activated条目,当选择/检查的项目,其将被使用。您还可以为其他状态指定颜色,上例从colors.xml表中引用颜色。
有关更多细节,请查看How does "?android:attr/activatedBackgroundIndicator" work?
你的意思是,在第12位的项目也改变颜色? – Nizam
你想用这段代码实现什么? –