Changing color of single drawable in RecyclerView will change all drawables

后端 未结 2 1519
执笔经年
执笔经年 2021-02-13 23:26

I just tried to change the color of my drawable inside my row depending on a value but instead of one drawable the adapter changed all of them.

Here is my Adapter:

相关标签:
2条回答
  • 2021-02-13 23:34

    Thanks to Sergey that guided me to the solution. I share what I did in onBindViewHolder method.

    final Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.ic_icon).mutate();
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        holder.image.setBackground(drawable);
    } else {
        holder.image.setBackgroundDrawable(drawable);
    }
    
    0 讨论(0)
  • 2021-02-13 23:50

    It's sort of caching. From the Android docs:

    if you instantiate two Drawable objects from the same image resource, then change a property (such as the alpha) for one of the Drawables, then it will also affect the other. So when dealing with multiple instances of an image resource, instead of directly transforming the Drawable, you should perform a tween animation.

    Drawable.mutate() after creating should fix the issue.

    A mutable drawable is guaranteed to not share its state with any other drawable. This is especially useful when you need to modify properties of drawables loaded from resources. 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.

    Something like this:

    Drawable box = ContextCompat.getDrawable(context, R.drawable.markbox).mutate();
    Drawable boxBorder = ContextCompat.getDrawable(context, R.drawable.markbox_border).mutate();
    
    0 讨论(0)
提交回复
热议问题