android - DrawableCompat setTint 为所有具有相同 id 的新 Drawable 着色

标签 android android-appcompat android-drawable tint

我有聊天气泡,我想在某些情况下对其进行着色:

Drawable bubbleDrawable = ContextCompat.getDrawable(context, R.drawable.bg_chat_bubble);

if (tint) {
    bubbleDrawable = DrawableCompat.wrap(bubbleDrawable);
    DrawableCompat.setTint(bubbleDrawable, bubbleTint);
}

问题是,一旦 R.drawable.bg_chat_bubble(它是一个 9 补丁)被着色,然后所有对 ContextCompat.getDrawable(context, R.drawable.bg_chat_bubble ) 返回着色图像而不是原始图像。即使当我关闭聊天并打开完全不同的聊天时,那里的气泡仍具有以前的色调。只有杀死应用程序才能帮助恢复正确的颜色。直到第一次染色...

即使在调用 setTint 后直接在 tint 分支中设置 bubbleDrawable = ContextCompat.getDrawable(context, R.drawable.bg_chat_bubble) 也会给出着色图像而不是原始图像.

我也试过 getResources().getDrawable(R.drawable.bg_chat_bubble) 但结果是一样的。因此,一旦我想为任何可绘制资源使用色调,我必须始终为该资源设置色调,否则我会得到不可预知的结果。

这发生在 Android 5.1(可能还有其他)以及 appcompat-v7:23.2.+appcompat-v7:23.1.+ 上。这是已知错误还是我做错了什么?

最佳答案

所有你需要的是在设置色调之前改变你的drawable:

bubbleDrawable.mutate()

Drawable.mutate

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.

关于android - DrawableCompat setTint 为所有具有相同 id 的新 Drawable 着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36279909/

相关文章:

android - 设计 Spinner、appcompat、material

android - 找不到 com.android.support :design-23. 2.1 和找不到 com.android.support.appcompat-v7-23.2.1 错误

android - 可绘制v21,v24?它是什么?

android - Material 图标: Scaling 48dp to 144dp limitations

android - ActionBar appcompat子菜单

android - 如何给按钮加上边框和点击效果?

从通知开始的 Android Pending Intent 不会替换最后一个

android - 在 android 屏幕上始终(从未被杀死)可见图标

android - 如何在 Android Q 上以编程方式安装 .apk?

java - 如何在 android 小部件 EditText 中添加水印?