【问题标题】:Custom SimpleCursorAdapter with background color for even rows具有偶数行背景颜色的自定义 SimpleCursorAdapter
【发布时间】:2012-08-31 21:47:51
【问题描述】:

我想实现一个自定义的 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));
        }
    }
}

一开始效果很好,但是当我反复向下和向上滚动列表时,所有行都变成蓝色。

提前致谢。

【问题讨论】:

    标签: android list listview background simplecursoradapter


    【解决方案1】:

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

    解决方案很简单,为奇数和偶数光标位置设置背景颜色。比如:

    @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));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-10
      • 2021-08-26
      • 1970-01-01
      • 2021-12-31
      • 2013-08-21
      • 1970-01-01
      • 2017-04-14
      • 2011-09-12
      • 1970-01-01
      相关资源
      最近更新 更多