setColorFilter有时在android drawable上不起作用 [英] setColorFilter is not working sometimes on android drawable

查看:402
本文介绍了setColorFilter有时在android drawable上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to apply color filter on drawable depending on selected primary color in preferences by user. This is the piece of code I am using.

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

问题在于,有时这段代码不会更改drawable的滤色器.我已将此代码放置在我的活动(主活动)onCreate和onResume方法中.

Problem is that, sometimes, this piece of code does not change the color filter of drawable. I have placed this code in my activity (main activity) onCreate and onResume method.

因此,一旦应用启动,我希望将此颜色滤镜应用到该可绘制对象上,但有时并没有发生.我还注意到,在高端移动设备(高速处理器,更多的RAM)上不会发生此问题,而只会在低端移动设备上发生.

So as soon as app launches, I want this color filter to be applied on that drawable but sometimes it is not happening. I also noticed that this problem is not happening on high end mobiles (high speed processor, more RAM) but only on low end mobiles.

但是,如果我浏览任何其他活动并返回到主要活动,则会应用滤色器.调试代码,并使用适当的颜色参数启动时调用setColorFilter,但是由于某种原因,它未得到应用.任何帮助都将受到赞赏.

But if I browse any other activity and come back to main activity, color filter gets applied. Debugged the code and setColorFilter is being called while launching with proper color parameter but for some reason it is not getting applied. Any kind of help is appreciated.

请不要拒绝这个问题,如果您认为这是一个愚蠢的问题,请发表评论,我将把这个问题记下来.我濒临被禁止问问题的问题.

Please do not downvote this question, if you think this is stupid question, just comment and I will take the question down. I am on the verge of getting banned on SO for asking question.

推荐答案

您尝试Drawable.mutate();像这样的财产

You try Drawable.mutate(); property like this,

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;
}

这篇关于setColorFilter有时在android drawable上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆