2013-04-25 81 views
0

我已經實現了列表項的自定義適配器。我有兩個要求列表項行顏色問題android

1)列表項目應該有替代顏色。要實現這一點,我有下面的代碼

private final int[] bgColors = new int[] {R.color.list_bg_1, R.color.list_bg_2};    
int colorPosition = position % bgColors.length; 
convertView.setBackgroundResource(bgColors[colorPosition]); 

2)當你點擊列表項,更應突出

Drawable selectedBackground; 
    selectedBackground = context.getResources().getDrawable(R.color.backgroundColor); 
    if (selectedPos == position) { 
       convertView.setBackgroundDrawable(selectedBackground); 
      } else { 
       convertView.setBackgroundDrawable(null); 
      } 

// this method is called in onItemClick in Activity. 
public void setSelectedPosition(int pos){ 
      selectedPos = pos; 
      notifyDataSetChanged(); 
     } 

問題:當我把兩個碼,任一功能不起作用。我怎樣才能確保這兩個功能與上面的代碼一起工作?

+0

看到這個[SO答案](http://stackoverflow.com/questions/2050533/list-items-with-alt ernating-顏色) – codeMagic 2013-04-25 02:22:42

回答

0

您應該爲背景創建一個selector.xml文件,然後將該視圖的背景設置爲該選擇器的名稱。選擇器可讓您爲視圖的每種狀態選擇背景;該視圖是否被選中,按下等

即 你有一個名爲my_views_background_selector

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:state_selected="true" 
    android:drawable="@drawable/selectedBackground" /> 
<item android:state_pressed="true" 
    android:drawable="@drawable/pressedBackground" /> 
<item android:drawable="@drawable/regularBackground"/> 


</selector> 

一個XML文件,那麼你可以通過做

convertView.setBackgroundResource(R.drawable.my_views_background_selector) 
編程設置背景

或者在你用來誇大你的轉換視圖的xml文件中