I'm implementing a CAB, and my ListView is populated from a database. When I scroll the ListView or rotate the device screen, the background of the previously selected items is reverted to the default background.
A holder which I use to store the selection status to restore it in bindView
:
private static class ViewInfo {
boolean selected;
}
bindView:
@Override
public void bindView(View view, Context context, Cursor cursor) {
view.setOnLongClickListener(mOnLongClickListener);
Object tag = view.getTag();
if (tag != null) {
ViewInfo info = (ViewInfo) view.getTag();
view.setSelected(info.selected);
} else {
view.setTag(new ViewInfo());
}
// Load data from the database here
}
OnLongClickListener:
mOnLongClickListener = new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
ViewInfo viewInfo = (ViewInfo) v.getTag();
v.setSelected(viewInfo.selected = !viewInfo.selected);
return true;
}
};
My ListView:
<ListView
android:id="@+id/filtering_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:choiceMode="multipleChoiceModal"
android:drawSelectorOnTop="true" />
My list item background filtering_list_item_bg:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/holo_blue_light" android:state_pressed="true"/>
<!-- pressed -->
<item android:drawable="@android:color/holo_blue_light" android:state_focused="true"/>
<!-- focused -->
<item android:drawable="@android:color/background_light" android:state_selected="true"/>
</selector>
My list item layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/filtering_list_item_bg"
android:paddingBottom="12dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="12dp" >
<!-- text views, image views, etc. -->
</RelativeLayout>
What I can't understand here is why setSelected
is called in bindView
but doesn't change the background.