Checkboxes Gets Unchecked In Recyclerview Upon Scrolling
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 ch
Solution 1:
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.
Solution 2:
use logic below on onBindView:
holder.attenCheckBox.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener() {
@OverridepublicvoidonCheckedChanged(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(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
if (holder.attenCheckBox.isChecked())
holder.attenCheckBox.setChecked(false);
else
holder.attenCheckBox.setChecked(true);
}
});
Explanation:
- Recycle view inflate eveytime when you scroll down or up.
- you need to store a flag in the data pojo to keep track of check status
- using that flag with
setOnCheckedChangeListener
will enable you to have you checkedenable/disable
. Make sure you put flag after listener.
Post a Comment for "Checkboxes Gets Unchecked In Recyclerview Upon Scrolling"