Read complete story

How to get only selected checkboxes in a RecyclerView

Hello Everyone, this one is again very easy to implement.
The issue I faced while using check-boxes inside a Recycler View is that when I check one of the checkboxes and scroll up or down, I see many other are selected and the reason for that is that Recycler View checks the checkbox according to the current view and the holder keeps that child selected. When you log or use the selected data you will find a lot more options than selected.

For a Recycler View to work fine you need to set an Adapter and that Adapter in turns calls the ViewHolder class and you override ” onBindViewHolder ” method of the Adapter to bind the view.
When you override this method you bind all the entities of the view that are of use to you and probably set all the listeners that need to work on any of the event triggered with respect to the entities of the view inflated.
But when you do the same with the check-boxes, they don’t work exactly the same as you want them to be.

APPROACH :

All you need to do is to change the state of checkbox as per the item of the list selected and hold that value.
Don’t just change the state of the checkbox.

And for each checkbox you need to first set the OnCheckedChangeListener to null.

Look at the piece of code and you will get it :

Just for a better insight , here is my full Adapter class:

Hope this works for you too.

Keep coding and keep sharing. : )

References : http://stackoverflow.com/questions/32427889/checkbox-in-recyclerview-keeps-on-checking-different-items

 

. . .

Comments (2)

Add Your Comment

  • Rohit
    What is the Suggestion class does not have isSelected field in it which you are updating? But I have a checkbox in my XML and during runtime I want to access the changed state of the checkbox?
    • anchit
      Hi Rohit,

      Well, if the Suggestion class does not have isSelected field in it.
      The best solution, I would say is to create it as that’s just a boolean reference.

      But Still, if you want to do it some other way or you cannot create any field in the class, then please do just share some sample code, so that I can look at the same and help you with some solution.

  • css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close