Recyclerview with checkbox in Android
Mahesh Gavale
Mobile App Developer || Android || Kotlin || Flutter || iOS-Swift || Fintech || Digital Banking
Those who all tried RecyclerView adapter with CheckBox, you all may find the issue on dynamic data change in RecyclerView. This will help you to resolve the issue in very simple way.
So how to achieve this task effectively?
Simple, I hope you all tried with list objects only. Surely this object will have the variable to know whether this object is selected or not. So now while we are select one object with the help of recyclerview and scroll down and up recyclerview adapter, the checked checkbox's position may change, this reflects on our object also, So how to avoid this issue.
Simple, In our recyclerview adapter's onBindViewHolder method, first set the checkedOnChangeListener of checkbox to null, and then set whether this object is selected or not to checkbox, and then add the checkedOnChangeListener to the checkbox. That's all. Issue solved.
will be look like
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
//in some cases, it will prevent unwanted situations
holder.checkbox.setOnCheckedChangeListener(null);
//if true, your checkbox will be selected, else unselected
holder.checkbox.setChecked(numbers.get(position).isSelected());
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
numbers.get(holder.getAdapterPosition()).setSelected(isChecked);
}
});
}
Note: Here numbers is list of objects.
I hope this post is useful to you. kindly share your feedback as comment here.
Thank You..!!
Psychologist & Software Programmer (Psychology tests) at FarsRavan.com AND Teacher (perimary education )
5 年so thanks?? holder.checkbox.setChecked(numbers.get(position).isSelected());? ?very helpful?
Frontend Developer (React Native)
5 年Thank you...it's worked in a greate way.
Sr. Android Developer | SOLID principles | DS | Problem Solving | Java | Kotlin | Rxjava | OOP | Jetpack | Unit Test | Room | Pen Test | RESTful APIs| GIT | CI/CD | DI | Design Pattern | Mobile Security | Multi-threading
6 年If I am not using Model class then , how to write this below line holder.checkbox.setChecked(numbers.get(position).isSelected());
Android Software Designer | Team Lead | Jetpack Compose | Multi-instrumentalist |
6 年It runs but with Kotlin and LayoutContainer extensions something weird happen