如果再次使用相同的可绘制对象,带有 colorFilter 的自定义 ImageView 会保留相同的过滤器

jus*_*ser 1 android android-layout

我有一个自定义图像视图,应该能够以编程方式或从布局设置图标的颜色。这有效。

假设我在黑色背景上使用白色图标。

然后,如果相同的图标可在应用程序的另一个位置绘制并反转颜色,白色背景上的黑色图标。这样,只有之前使用过的图标才会保持原来的颜色。我无法从布局或以编程方式更改它。相同的活动但不同的片段。

这就是班级。

public class IconView extends ImageView {

    public IconView(Context context) {
        this(context, null);
    }

    public IconView(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.iconViewStyle);
    }

    public IconView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.IconView, defStyle, 0);
        int color = attributes.getColor(R.styleable.IconView_icon_color, Color.WHITE);
        ColorFilter cf = new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN);
        if (getDrawable() != null) getDrawable().setColorFilter(cf);
        attributes.recycle();
    }

    public void setIconColor(int color) {
        getDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
    }
}
Run Code Online (Sandbox Code Playgroud)

我是不是做错了什么,或者android可能会以某种方式重用drawables,一旦它们被绘制,它们就会保持这种状态(看起来很奇怪)!

Mar*_*per 5

我知道另一个答案已被选为正确的答案,但在我看来,您遇到的问题与答案所暗示的内容不同。如果您在同一活动中使用相同的图像(特别是来自资源的图像),那么当您应用颜色滤镜时,所有这些图像都将被修改。这是因为 res 中的可绘制对象是不可变的,并且将共享相同的状态。为了避免这种情况,请使用getDrawable().mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN).

的文档mutate()包含有关此的更多信息。