自定义SimpleCursorAdapter,背景颜色为偶数行

use*_*981 1 android listview background list simplecursoradapter

我想实现一个自定义SimpleCursorAdapter,它只在偶数行上显示背景颜色(在我的情况下为蓝色).我的实现如下:

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它在开始时工作正常,但是当我反复向下滚动列表时,所有行都变为蓝色.

提前致谢.

new*_*yca 6

滚动时适配器回收(重用)项目视图.这意味着当您滚动列表来回时,不能保证相同的项目视图将用于给定的光标位置.在您的情况下,如果当前位置是偶数,则仅设置项目视图的背景颜色,但是您当前正在处理的特定视图可能先前已在奇数位置使用.因此,随着时间的推移,所有项目视图都获得相同的背景颜色.

解决方案很简单,设置奇数和偶数光标位置的背景颜色.就像是:

@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));
    }else{
        view.setBackgroundColor(
                Color.parseColor(someOtherBackgroundColor));
    }
}
Run Code Online (Sandbox Code Playgroud)