I have a cursor which retrieves a list of ingredients and populates an adapter, which is then assigned to a recycler View having checkboxes. The problem I've got is that, when I check a set of checkboxes and scroll down, the ones selected from the top, get deselected and vice versa, or in some instances, if I select three from the top, three from the bottom get selected. I need to make sure that, initially nothing is selected, and even if I scroll up and down, the ones selected should remain selected and need to keep track of.
Here is the list which is scrolable.
Here is my code:
class RecipeDetailCursorAdapter extends CursorRecyclerViewAdapter<RecyclerView.ViewHolder> {
private int mBrownColor;
private int mGreenColor;
private int mCheckItems;
private ItemsCheckedCallback mCheckedCallback;
RecipeDetailCursorAdapter(Context context, Cursor cursor, ItemsCheckedCallback callback) {
super(context, cursor);
mCheckedCallback = callback;
mBrownColor = ContextCompat.getColor(mContext, R.color.colorTextBrown);
mGreenColor = ContextCompat.getColor(mContext, R.color.colorTextGreen);
mCheckItems = 0;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, Cursor cursor) {
String taskName = cursor.getString(cursor.getColumnIndexOrThrow(MascotHelper.RecipeTask.NAME));
((RecipeTaskHolder) viewHolder).bindView(taskName);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recipe_task_item, parent, false);
return new RecipeTaskHolder(v);
}
private class RecipeTaskHolder extends RecyclerView.ViewHolder
implements SmoothCheckBox.OnCheckedChangeListener {
SmoothCheckBox taskBox;
TextView recipeComponentName;
RecipeTaskHolder(View v) {
super(v);
taskBox = (SmoothCheckBox) v.findViewById(R.id.recipe_task_box);
recipeComponentName = (TextView) v.findViewById(R.id.recipe_component_name);
taskBox.setOnCheckedChangeListener(this);
}
void bindView(String task) {
recipeComponentName.setText(task);
}
@Override
public void onCheckedChanged(SmoothCheckBox smoothCheckBox, boolean b) {
if (smoothCheckBox.isChecked()) {
recipeComponentName.setTextColor(mBrownColor);
mCheckItems++;
} else {
recipeComponentName.setTextColor(mGreenColor);
mCheckItems--;
}
if (mCheckItems == getItemCount()) {
//Toast.makeText(mContext, "All items are checked", Toast.LENGTH_SHORT).show();
mCheckedCallback.onAllItemChecked(true);
} else {
mCheckedCallback.onAllItemChecked(false);
}
}
}
interface ItemsCheckedCallback {
void onAllItemChecked(boolean status);
}
}
Any ideas or suggestions would be appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…