2012-05-04 288 views
3

我見過很多simillar問題,每個答案都是非常具體的問題,並沒有直接的答案,或者我找到了教程,展示如何創建一個複選框,選中項目進行檢查。 而且我無法理解如何從這些代碼中完成它。如何更改ListView中選定項目的背景顏色?

我正在關注一個發現Here的教程,這很像我的代碼看起來只有不同的名字。

我想要有一個多選擇ListView,當一個項目選擇了背景顏色被改變來標記我選擇的項目。

也許我可以使用自定義選擇器來實現這一點? 我明白常用的方法是保存所選位置並在getView函數中執行某些操作。 我看到有人在創建ViewHolder,但我並不真正瞭解它與什麼有關。 有人可以幫我嗎?

預先感謝, 埃裏克

回答

13

嗯,我終於解決了這個問題,希望這可以幫助別人:

我所做的就是創建一個ArrayList<Integer>存儲所選項目的所有位置,以及切換背景顏色點擊次數。

以我適配器我定義:

public ArrayList<Integer> selectedIds = new ArrayList<Integer>(); 

以下方法:

public void toggleSelected(Integer position) 
{ 
    if(selectedIds.contains(position)) 
    { 
     selectedIds.remove(position); 


    } 
    else 
    { 
     selectedIds.add(position); 
    } 
} 

其中就將此\從該ArrayList

移除項以我getView方法:

  if (selectedIds.contains(position)) { 
      convertView.setSelected(true); 
      convertView.setPressed(true); 
      convertView.setBackgroundColor(Color.parseColor("#FF9912")); 
     } 
     else 
     { 
      convertView.setSelected(false); 
      convertView.setPressed(false); 
      convertView.setBackgroundColor(Color.parseColor("#000000")); 
     } 

這將檢查該位置是否存儲在ArrayList中。如果是,則將其繪製爲選定的。如果不是,則相反。

所有剩下的只有OnItemClick聽者,我說:

((YourAdapter)list.getAdapter()).toggleSelected(new Integer(position)); 

當YourAdapter是你的ListView

希望的適配器,這可以幫助任何人,因爲它是一個通用的答案:)

+0

我面臨着同樣的問題,但是在您的解決方案中,我無法理解什麼是「列表」? – Rohit

+0

這就是我在OnItemClick事件中命名的方式 –

+0

完美的答案,非常感謝! – Claud

0

您還可以將以下選擇器設置爲背景以列出項目佈局:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_selected="true" android:drawable="@color/android:transparent" /> 
    <item android:drawable="@drawable/listitem_normal" /> 
</selector> 

來源:ListView item background via custom selector

0

有一個普通的XML解決方案。下面的語法是WRT API 15 我用下面的列表項的模板:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@drawable/item_selection"> 
    <ImageView /> 
    <.. /> 
</LinearLayout> 

它指向在res文件item_selection.xml /提拉 - 華電國際(Android Studio中0.8。14):

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

    <item android:drawable="@android:color/holo_blue_dark" android:state_selected="true" /> 
</selector> 
相關問題