CursorAdapter - 列出beheivour

时间:2016-09-16 09:58:39

标签: android android-cursoradapter

我使用CursorAdapter为我的列表添加一个自定义布局,具体取决于我的表的字段值(true或false),列表项中其中一个textviews的颜色将不同。

public class CustomAdapter extends CursorAdapter {
    DatabaseHelper myDB;
    SQLiteDatabase db;

public CustomAdapter(Context context, Cursor cursor, int flags) {
    super(context, cursor, 0);
    myDB = new DatabaseHelper(context, DatabaseHelper.DB_NAME, null, DatabaseHelper.DB_VERSION_SCHEME);
    db = myDB.getReadableDatabase();
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return LayoutInflater.from(context).inflate(R.layout.customize_cell_list, parent, false);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {

    TextView tv = (TextView) view.findViewById(R.id.tv);
    TextView tv_date = (TextView) view.findViewById(R.id.tvDateCursor);
    TextView tv_time = (TextView) view.findViewById(R.id.tvTime);
    ImageView img = (ImageView)view.findViewById(R.id.img);

    if(cursor != null) {
        String tv = cursor.getString(2);
        String date = cursor.getString(3);
        String time = cursor.getString(8);
        boolean active = cursor.getInt(12) > 0;
        boolean go = cursor.getInt(13) > 0;

        tv_date.setText(date);
        tv.setText(tv);

        if(go) { // OPTION 1
            img.setImageResource(R.drawable.calle);
            tv_time.setText(time);

        } else { // OPTION 2
            img.setImageResource(R.drawable.casa);

            if(active){  // OPTION 2.1
                tv_time.setText("Activado");
            }else{  // OPTION 2.2
                tv_time.setText("No activado");
                tv_time.setTextColor(Color.RED);
            }
        }
    } 
}
}

结果:图像显示正确的文本视图,问题是颜色,当我有一个项目与OPTION 2.2并开始向上和向下滚动我的一些tv_time(甚至从选项1)开始要将颜色更改为红色,然后我再次滚动它们变为白色而其他颜色变为红色,这是随机的。

为什么会这样?我怎样才能在"去"和"活跃"是假的?

由于

1 个答案:

答案 0 :(得分:0)

您需要记住以下事项 1. ListView中的视图是有限的。 2.每当您滚动可见性消失的视图时,将使用后面的项目更新,然后它将返回到视图

所以现在你根据一些标准设置颜色。当你绑定视图时,你正在设置颜色。 确保解除视图绑定后,您将使视图恢复原始颜色。如果您不这样做,View在失去其可见性时仍然包含颜色,并且当其他数据项被提取到其中时看起来是红色。

因此,首先检查绑定是否为红色。如果是,那么检查你想保持红色,是的,保持它,然后没有,然后让它恢复原来的颜色