PorterDuffColorFilter 更改我的 recyclerview 中的所有图标

PorterDuffColorFilter changes all icons in my recyclerview

所以 - 我有一个 recyclerview,如果我点击一个项目,我想更改我的 drawable 的 colorFilter,它在我点击的位置附加到我的 textView。

问题是,当我更改可绘制对象的颜色时,所有项目都会发生变化,而不仅仅是单击的位置。

代码:

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

在我的适配器的 'onBindViewHolder' 中调用这个 for 循环,当我点击时 - 我正在用我的位置调用 notifyItemChanged,我已经三次检查它,这个函数只运行一个单次点击我的正确位置..那为什么一切都变了?

根据 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.

您需要使用 mutate() 方法获取不再共享状态的可绘制对象的新实例(实际上大多数时候只有状态是新的)。