androidandroid-recyclerviewandroid-viewholdersectionedrecyclerviewadapter

Android | Update RecyclerView Adapter on ViewHolder onClick


I expect my 'heart' icon to change when my ViewHolder item is clicked. Fortunately, it does this. However, an issue arises as multiple items seems to replicate the button click.

What I mean is: If I tap the heart on item number 1. Other items throughout the list replicate also change the heart. Why is this happening and what is a potential fix? I am confused why this issue is occuring as I am referencing the ViewHolder item. Thus, shouldn't it only affect the item I am clicking?

View Holder

        fun bind(item: Location) {
            heart.setOnClickListener {
                item.fav = item.fav != true
                heart.setImageDrawable(
                when (item.fav) {
                    false -> (ContextCompat.getDrawable(itemView.context, R.drawable.ic_border_heart))
                    else -> (ContextCompat.getDrawable(itemView.context, R.drawable.ic_whole_heart))
                })

            }
        }

Solution

  • onBindViewHolder you need to save list of fave in change item image base on that list otherwise it changes randomly as view recreates

         fun bind(item: Location) {
    
     heart.setImageDrawable(
                    when (item.fav) {
                        false -> (ContextCompat.getDrawable(itemView.context, R.drawable.ic_border_heart))
                        else -> (ContextCompat.getDrawable(itemView.context, R.drawable.ic_whole_heart))
                    })
                heart.setOnClickListener {
                    item.fav = item.fav != true
                    heart.setImageDrawable(
                    when (item.fav) {
                        false -> (ContextCompat.getDrawable(itemView.context, R.drawable.ic_border_heart))
                        else -> (ContextCompat.getDrawable(itemView.context, R.drawable.ic_whole_heart))
                    })
    
                }
            }