我有一个主细节 ListView 设置,我想更改主片段中选定项目的背景。
我曾经有以下代码,但这不允许我使用成熟的选择器:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
// Highlight selected item
if (position == selectedPos) {
view.setBackgroundColor((view.getResources()
.getColor(R.color.nw_white)));
} else {
view.setBackgroundColor((view.getResources()
.getColor(R.color.nw_grey)));
}
return view;
}
它工作正常,但我想使用选择器。(因为我希望项目在焦点和点击时适当地改变背景。)
所以我把它改成:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
// Highlight selected item
if (position == selectedPos) {
view.setSelected(true);
// view.setBackgroundColor((view.getResources()
// .getColor(R.color.nw_row_download_master_selected)));
} else {
view.setSelected(false);
// view.setBackgroundColor((view.getResources()
// .getColor(R.color.nw_row_download_master_normal)));
}
Log.d(TAG, "pos " + position + " is selected: "
+ view.isSelected());
return view;
}
列表行如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/selector_row_collection_master"
android:orientation="horizontal"
>
...
</LinearLayout>
和这样的选择器:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/row_master_detail_pressed"
android:state_pressed="true" />
<item android:drawable="@drawable/row_master_detail_focused"
android:state_focused="true" />
<item android:drawable="@color/nw_row_master_master_selected"
android:state_selected="true" />
<item android:drawable="@color/nw_row_master_normal" />
</selector>
该行响应单击事件但不响应被选中,即使记录器说视图确实被选中!到底是怎么回事?