列表项行颜色问题android

时间:2013-04-25 02:18:44

标签: android list click

我为列表项实现了自定义适配器。我有两个要求

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();
        }

问题:当我输入两个代码时,任何一个功能都无法正常工作。我怎样才能确保这两个功能都适用于上面的代码?

1 个答案:

答案 0 :(得分:0)

您应该为背景创建一个selector.xml文件,然后将视图的背景设置为该选择器名称。选择器允许您为视图的每个状态选择背景;是否选择,按下等视图

即, 你有一个名为my_views_background_selector

的xml文件
<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>

然后你可以通过编程

以编程方式设置背景
convertView.setBackgroundResource(R.drawable.my_views_background_selector)

或者用于扩充convertView

的xml文件