2012-01-09 90 views
-1

我想在列表視圖中設置條目的替代顏色。我嘗試使用setBackgroundColor和setBackgroundResource,但我似乎只獲得透明背景。以編程方式設置listview的背景顏色

public View getView(final int position, View convertView, ViewGroup parent) { 
      if (convertView == null) { 
        convertView = inflateView(R.layout.pending_list); 
        if(position % 2 != 0){ 
         convertView.setBackgroundResource(R.drawable.list_item_odd); 
        } else { 
         convertView.setBackgroundResource(R.drawable.list_item_even); 
      } 
      return convertView; 
     } 
    } 

這是list_item_odd.xml

<item android:state_pressed="true"><shape> 
     <solid android:color="@color/blue" /> 
    </shape></item> 
<item android:state_focused="true"><shape> 
     <solid android:color="@color/blue" /> 
    </shape></item> 
<item><shape> 
     <solid android:color="@color/bluish" /> 
    </shape></item> 

,這是colors.xml文件

<resources xmlns:android="http://schemas.android.com/apk/res/android" > 

<color name="blue">#006C9C</color> 
<color name="white">#ffffff</color> 
<color name="whitish">#FDFDFD</color> 
<color name="bluish">#F2F9FD</color> 

</resources> 

我無法弄清楚爲什麼我收到這個結果呢。

+1

[更改Android上的ListView項目的背景顏色]的可能重複(http://stackoverflow.com/questions/2217753/changing-background-color-of-listview- items-on-android) – 2012-01-09 18:04:58

+0

list_item_odd.xml是一個選擇器刪除它,並以適當的方式做到這一點。它的工作原理是 – 2012-01-09 18:18:37

+0

。空檢查後我必須setbackgroundresource – Amit 2012-01-09 18:42:44

回答

1

這對我的作品

private int[] listdrawable ={R.drawable.list_backgroung, R.drawable.list_backgroung1111}; //list of drawable background 

    int colorPos = position % listdrawable.length; //in getView() method before setting the values 
    convertView.setBackgroundResource(listdrawable[colorPos]); 

reurn convertView;