I have a master-detail ListView set-up, and I want to to change the background for selected items in the master fragment.
I used to have the following code, but this does not allow me to use a full-fledged selector:
@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;
}
It works fine, but I want to use selectors. (Because I want the items to change background appropriately on focus and click.)
So I changed it to:
@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;
}
Where the list rows look like this:
<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>
And the selector like this:
<?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>
The row responds to click events but not to being selected, even though the logger says that the view, indeed, is selected! What is going on?