我正在创建一个包含项目的RecyclerView
。每个项目都有CheckBox
,ImageButton
和TextView
,如下所述:
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
,而不是每一行。我该如何做到这一点?
答案 0 :(得分:2)
问题是您正在遍历游标中的每一行。相反,您需要通过调用cursor.moveToPosition()
转到当前position
的行。
在伪代码中,您应遵循的步骤是
Checkbox
设置为正确的状态。我将细节作为练习留给读者。
答案 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.