androidandroid-recyclerviewandroid-adapterporter-duffcolorfilter

PorterDuffColorFilter changes all icons in my recyclerview


so - I have a recyclerview and if I click on an item I want to change the colorFilter of my drawable that is attached to my textView in the position clicked.

the problem is, when I change the color of my drawable, it changes in all items instead of only the position clicked.

code:

for (drawable: Drawable? in textView.compoundDrawablesRelative) {
    drawable?.colorFilter = PorterDuffColorFilter(getColor(textView.context, color), PorterDuff.Mode.SRC_IN)
}

this for-loop is being called in the 'onBindViewHolder' of my adapter, when I'm clicking - I'm calling notifyItemChanged with my position, I've triple checked it, this function only runs a single time with my correct position clicked.. so why does everything changes?


Solution

  • As per the documentation of Drawable:

    By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification.

    You need to get a new instance (actually only the state is new most of the times) of that drawable which doesn't share the state anymore using the mutate() method.