加载后检查RecyclerView中的CheckBox

时间:2016-06-08 02:44:02

标签: android android-studio android-recyclerview android-checkbox

我正在创建一个包含项目的RecyclerView。每个项目都有CheckBoxImageButtonTextView,如下所述:

public class RecyclerViewViewHolder extends RecyclerView.ViewHolder {
    RelativeLayout item;
    TextView id;
    TextView name;
    ImageButton delete;
    CheckBox checkBox;

    public RecyclerViewViewHolder(View view) {
        super(view);

        item = (RelativeLayout) view.findViewById(R.id.layout_item_item);
        id = (TextView) view.findViewById(R.id.layout_item_id);
        name = (TextView) view.findViewById(R.id.layout_item_name);
        delete = (ImageButton) view.findViewById(R.id.layout_item_delete);
        checkBox = (CheckBox) view.findViewById(R.id.layout_item_checkbox);
    }
}

我希望仅当数据库列中的某个值等于checkbox时才会检查1视图。如果值为0,则不应检查该值。我已经开始使用以下代码:

SQLiteDatabaseAdapter database = new SQLiteDatabaseAdapter(context);
    database.open();

    Cursor cursor = database.getAllItems(table);

    if (cursor.moveToFirst()) {
        do {
            if (cursor.getInt(2) == 0) {
                viewHolder.checkBox.setChecked(false);
            }

            else {
                viewHolder.checkBox.setChecked(true);
            }

        } while (cursor.moveToNext());

    }

    database.close();

此代码有效,但会检查数据库中的第一行,如果checked列为1,则会更改每个CheckBox进行检查。我只希望检查与一个特定行关联的CheckBox,而不是每一行。我该如何做到这一点?

2 个答案:

答案 0 :(得分:2)

问题是您正在遍历游标中的每一行。相反,您需要通过调用cursor.moveToPosition()转到当前position的行。

在伪代码中,您应遵循的步骤是

  1. 打开数据库。
  2. 获取光标。
  3. 将光标移动到正确的行。
  4. 从光标中检索值。
  5. Checkbox设置为正确的状态。
  6. 关闭光标。
  7. 我将细节作为练习留给读者。

答案 1 :(得分:1)

I recommend that you create a HashMap<> and link the IDs and the checked states. Then, you can reference from the HashMap<> and get the checked states.

HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();

Then, in your onBindViewHolder function, you can use the following to check you CheckBox:

if (hashMap.get(position) == 0) {
    // not checked
}

else {
    // checked
}

Make sure you add the IDs and checked states from your SQLite database.