为什么drawable color filter 应用在​​所有地方?

Why drawable color filter is applied in all places?

在我的应用程序的一部分中,我需要将我的可绘制对象 R.drawable.blah 过滤为白色(最初是红色),所以我有这个方法:

public final static Drawable getFilteredDrawable(Context context, @DrawableRes int drawable, @ColorRes int color) {
    Drawable d = ContextCompat.getDrawable(context, drawable);
    d.setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_IN);
    return d;
}

我是这样使用的:

DrawableUtil.getFilteredDrawable(this, R.drawable.blah, android.R.color.white);

问题是现在 drawable 在整个应用程序中变成了白色,甚至没有应用过滤器。我希望应用程序的这一部分中的可绘制对象是白色的,但在我使用它的每个地方都是白色的。

我该如何解决?

改用此方法,以确保您使用的是可绘制对象的副本

public final static Drawable  getFilteredDrawable(Context context, @DrawableRes int drawable, @ColorRes int color) {
    Drawable d = ContextCompat.getDrawable(context, drawable).getConstantState().newDrawable().mutate(); //so we are sure we are using a copy of the original drawable
    d.setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_IN);
    return d;
}