2013-10-30 142 views
0

以下腳本設置(例如)ListItem位置1的顏色,但它也給號碼12(11 + 1)一個很好的灰色。這是Android中的某種錯誤嗎?onItemClick列表視圖設置2個項目的顏色

@Override 
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 
    ListView.setSelection(arg2); 
    arg1.setBackgroundColor(Color.LTGRAY); 
    adapter.notifyDataSetChanged(); 
} 
+0

你的意思是,在第12位的項目也改變顏色? – Nizam

+0

你想用這段代碼實現什麼? –

回答

1

ListView回收(重新使用)的意見。因此,您需要將背景顏色與數據關聯,而不是視圖!然後,在getView()中,您有機會根據數據正確設置背景顏色。

0

@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?

相關問題