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, w
use logic below on onBindView:
holder.attenCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (holder.attenCheckBox.isChecked())
dataModel.setChecked(true);
else
dataModel.setChecked(false);
}
});
if (dataModel.getChecked())
holder.attenCheckBox.setChecked(true);
else
holder.attenCheckBox.setChecked(false);
holder.checkboxLinearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (holder.attenCheckBox.isChecked())
holder.attenCheckBox.setChecked(false);
else
holder.attenCheckBox.setChecked(true);
}
});
Explanation:
setOnCheckedChangeListener
will enable you to have you checked enable/disable
. Make sure you put flag after listener.RecyclerView removes (recycles) the unseen views from the layout on scrolling, this is the basic behavior of recyclerView in order to reduce memory use.
When a view with a checkbox is recycled, a checked checkbox gets unchecked and if it has a listener, the listener gets called.
You can remove the listener from the view when it is recycled. Just override the onViewRecycled method.
@Override
public void onViewRecycled(@NonNull MyViewHolder holder) {
holder.checkBox.setOnCheckedChangeListener(null);
super.onViewRecycled(holder);
}
When the view is constructed again, while scrolling, your listener will also be added again.