2013-04-25 41 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文件中