@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
你想用這段代碼實現什麼? –