CheckBox in RecyclerView not working as expected

I used imageView and checkbox above image view as one row in RecyclerView. I have set the background of the checkbox as shown below. After displaying the lines, when I check the box for a specific position, the image changes at that position, but at the same time the same effect happens in a different location, which I did not check.

Please help me figure out the error, I don't understand what is 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>

      

+3


source to share


1 answer


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

  • have an "isChecked" attribute on your object that the data list is made of.
  • implementation in state changed for checkbox and synchronization of recently updated state with isChecked checkbox of current object
  • when you bind the holder of your view, check if the flag is true or false and update the layout to match the flag.


Hope you get this to work, hurray!

+2


source







All Articles