setColorFilter is not working sometimes on android drawable

╄→гoц情女王★ 提交于 2020-01-02 19:10:11

问题


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

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.

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.

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.


回答1:


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


来源:https://stackoverflow.com/questions/44984488/setcolorfilter-is-not-working-sometimes-on-android-drawable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!