我有列表视图,我在其中设置备用背景颜色。现在我想在列表项单击上使用列表选择器。 这是我使用游标适配器的getView()设置备用背景的方式
的CursorAdapter
public View getView(int position, View convertView, ViewGroup parent) {
final View row = super.getView(position, convertView, parent);
if (position % 2 == 0)
row.setBackgroundColor(Color.parseColor("#191919"));
else
row.setBackgroundColor(Color.parseColor("#323232"));
return row;
}
list_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/list_item_bg_normal" android:state_activated="false"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_activated="true"/>
</selector>
list_item_bg_pressed.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
list_item_bg_normal.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#00000000" /> <!-- transparent -->
</shape>
最后我有我的列表视图,其中我使用了listSelector。
activity.xml
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/myListView"
android:listSelector="@drawable/list_selector"
android:drawSelectorOnTop="true"
android:clickable="true"/>
我无法解决这个问题。我不知道哪里出错了。
我的屏幕输出就像这样
答案 0 :(得分:0)
Try like this instead of drawable:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#00000000" android:state_activated="false"/>
<item android:drawable="#FF0000" android:state_pressed="true"/>
<item android:drawable="#FF0000" android:state_activated="true"/>
</selector>
答案 1 :(得分:0)
最后,我找到了答案。我创建了两个选择器XML文件来提供备用背景。看到这个。
selector_one
<?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/black1" />
<item android:state_pressed="true" android:drawable="@android:color/holo_red_dark" />
<item android:state_selected="true" android:state_pressed="false" android:drawable="@android:color/holo_red_dark" />
</selector>
selector_two
<?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/black2" />
<item android:state_pressed="true" android:drawable="@android:color/holo_red_dark" />
<item android:state_selected="true" android:state_pressed="false" android:drawable="@android:color/holo_red_dark" />
</selector>
并且在适配器的getView()方法中我调用了两个选择器。
if (position % 2 == 0) {
convertView.setBackgroundResource(R.drawable.selector_one);
} else {
convertView.setBackgroundResource(R.drawable.selector_two);
}
我参考了这个Link