Rahul
Rahul

Reputation: 395

CheckBox in a RecyclerView not functioning properly

I have used an imageView and a checkbox over the imageview as a single row in a RecyclerView. I have put the background of the checkbox as below codes. After displaying the rows, when I m checking the checkbox for a particular position the image is changing in that position but simultaneously same effect is also occurring in some other position which i have not checked.

Help to figure out the error, I m not getting whats wrong.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
    android:drawable="@drawable/ic_love_dark_red" /> <!-- pressed -->
<item android:state_checked="false"
    android:drawable="@drawable/ic_love_holo_blank" /> <!-- focused -->
<item android:drawable="@drawable/ic_love_holo_blank" />
</selector>

Upvotes: 3

Views: 2325

Answers (1)

DDsix
DDsix

Reputation: 1984

You cannot have this functionality (change the picture on state changed) made in xml file because a single instance of the CheckBox widget will be used multiple times in your RecyclerView, depending on the size of data it is displaying. Basically, RecyclerView uses View Holder pattern (of which I invite you to read about if you're not familiar with it), thus making the image change on multiple rows. What you need to do:

  • have an "isChecked" attribute in your object of which the data list is made
  • implement on state changed for the check box and synchronize the newly updated state with the isChecked flag of the current object
  • when you bind your view holder, check whether the flag is true or false and update the layout according to the flag.

Hope you get it to work, cheers!

Upvotes: 2

Related Questions