I would like to implement a custom SimpleCursorAdapter which shows a background color (blue in my case) only on even rows. My implementation is as follows:
public class ColoredCursorAdapter extends SimpleCursorAdapter {
String backgroundColor;
public ColoredCursorAdapter(
Context context,
int layout,
String backgroundColor,
Cursor c,
String[] from,
int[] to,
int flags) {
super(
context,
layout,
c,
from,
to,
flags);
this.backgroundColor = backgroundColor;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
if(cursor.getPosition() % 2 == 0) {
view.setBackgroundColor(
Color.parseColor(backgroundColor));
}
}
}
It works fine at the start, but when I repeatedly scroll down and up the list, all rows become blue.
Thanks in advance.
Adapters recycle (reuse) item views as you scroll around. What this means is that you’re not guaranteed the same item view will be used for a given cursor position as you scroll a list back and forth. In your case, you only set the item view’s background color if the current position is even, however the particular view you’re currently dealing with may have previously been used at an odd numbered position. Thus, over time all your item views acquire the same background color.
The solution is simple though, set the background color for both odd and even cursor positions. Something like: