setColorFilter 有时无法在 android 可绘制对象上工作

setColorFilter is not working sometimes on android drawable

我正在尝试根据用户在首选项中选择的原色在可绘制对象上应用滤色器。这是我正在使用的代码。

getResources().getDrawable(R.drawable.ic_batman_1)
            .setColorFilter(ColorHelper.getPrimaryColor(), PorterDuff.Mode.OVERLAY);

问题是,有时,这段代码不会更改可绘制对象的颜色过滤器。我已将这段代码放在我的 activity (main activity) onCreate 和 onResume 方法中。

因此,一旦应用程序启动,我希望将此滤色器应用到该可绘制对象上,但有时它不会发生。我还注意到这个问题不会发生在高端手机(高速处理器,更多 RAM)上,只会发生在低端手机上。

但是,如果我浏览任何其他 activity 并返回主要 activity,则会应用滤色器。调试代码并在使用正确的颜色参数启动时调用 setColorFilter 但由于某种原因它没有被应用。感谢任何形式的帮助。

请不要对这个问题投反对票,如果你认为这是一个愚蠢的问题,请发表评论,我会把这个问题记下来。我正处于被禁止在 SO 上提问的边缘。

你试试Drawable.mutate(); 属性像这样,

Drawable drawable = ContextCompat.getDrawable(context, resource).mutate();

drawable.setColorFilter(ColorHelper.getPrimaryColor(), PorterDuff.Mode. OVERLAY);
/**
 * Make this drawable mutable. This operation cannot be reversed. 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.
 *
 * Calling this method on a mutable Drawable will have no effect.
 *
 * @return This drawable.
 * @see ConstantState
 * @see #getConstantState()
 */
public @NonNull Drawable mutate() {
    return this;
}