Recyclerview with checkbox in Android

Recyclerview with checkbox in Android

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..!!


Sadegh Zarghami

Psychologist & Software Programmer (Psychology tests) at FarsRavan.com AND Teacher (perimary education )

5 年

so thanks?? holder.checkbox.setChecked(numbers.get(position).isSelected());? ?very helpful?

回复
Neha Kansagara

Frontend Developer (React Native)

5 年

Thank you...it's worked in a greate way.

回复
Pooja Kumari

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());

回复
Carlos Cervantes Bedoy

Android Software Designer | Team Lead | Jetpack Compose | Multi-instrumentalist |

6 年

It runs but with Kotlin and LayoutContainer extensions something weird happen

回复

要查看或添加评论,请登录

Mahesh Gavale的更多文章

社区洞察

其他会员也浏览了