setColorFilter 有时在 android drawable 上不起作用

Ami*_*ari 2 java android drawable colorfilter

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

getResources().getDrawable(R.drawable.ic_batman_1)
            .setColorFilter(ColorHelper.getPrimaryColor(), PorterDuff.Mode.OVERLAY);
Run Code Online (Sandbox Code Playgroud)

问题是,有时,这段代码并没有改变 drawable 的颜色过滤器。我已将此代码放在我的活动(主要活动)的 onCreate 和 onResume 方法中。

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

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

请不要贬低这个问题,如果您认为这是一个愚蠢的问题,请发表评论,我会撤下这个问题。我即将被禁止在 SO 上提问。

Mut*_*ran 5

你试试 Drawable.mutate(); 这样的财产,

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

drawable.setColorFilter(ColorHelper.getPrimaryColor(), PorterDuff.Mode. OVERLAY);
Run Code Online (Sandbox Code Playgroud)
/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)