android listview交替行颜色但是默认光标选择

use*_*402 3 android listview row colors alternate

我已经遍布网络,包括stackoverflow,似乎无法得到一个明确的完整方式

我想创建一个ListView

1)有交替的颜色(我可以用下面的代码做到这一点)2)保留android的默认橙色选择行为

完成#1我有一个扩展ArrayAdapter的自定义适配器,然后我像这样重写getView

public View getView(int position,  View convertView,   ViewGroup parent)
{
  ....

  // tableLayoutId is id pointing to each view/row in my list
  View tableLayoutView = view.findViewById(R.id.tableLayoutId); 
  if(tableLayoutView != null)
  {
      int colorPos = position % colors.length;
      tableLayoutView.setBackgroundColor(colors[colorPos]);
  }
}
Run Code Online (Sandbox Code Playgroud)

我的颜色成员变量是

private int[] colors = new int[] { 0x30ffffff, 0x30ff2020, 0x30808080 };
Run Code Online (Sandbox Code Playgroud)

此处找到文章"Android - 在ListView中使用SimpleAdapter应用备用行颜色"

现在这是我被卡住的地方,我在stackoverflow上看到一些提到这样做,因为它会看到常见的,他们建议将此属性添加到

机器人:listSelector = "@颜色/ LIST_ITEM"

list_item.xml就像这样

<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_selected="true"
    android:drawable="@drawable/transparent" />
   .....
 </selector>
Run Code Online (Sandbox Code Playgroud)

然后我必须向getView()添加代码以确定我所处的状态并采取相应的行动.

有没有一个例子让这个工作?谢谢大家,我很乐意发布我的所有内容,如果我可以让它工作.:-(

小智 8

解决方法是使用2个选择器.从适配器中,您可以设置2个选择器,而不是设置2种颜色.

if (position % 2 == 0) {
  view.setBackgroundResource(R.drawable.selector_1);
} else {
  view.setBackgroundResource(R.drawable.selector_2);
}
Run Code Online (Sandbox Code Playgroud)

selector_1在selector_1.xml中定义如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="false" android:state_pressed="false"  android:drawable="@color/white" />
<item android:state_pressed="true" android:drawable="@color/orange" />
<item android:state_selected="true" android:state_pressed="false"  android:drawable="@color/orange" />
</selector>
Run Code Online (Sandbox Code Playgroud)

selector_2在selector_2.xml中定义如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="false" android:state_pressed="false"  android:drawable="@color/violet" />
<item android:state_pressed="true" android:drawable="@color/orange" />
<item android:state_selected="true" android:state_pressed="false"  android:drawable="@color/orange" />
</selector>
Run Code Online (Sandbox Code Playgroud)

所以,你有一个双色列表视图和第三个颜色/形状/你想要的所选项目.