Android:为三个图标之一着色

标签 android drawable android-drawable android-resources android-vectordrawable

我需要 3 个图标:ContextCompat.getDrawable(this, R.drawable.my_vector_drawable)

第一个 - 无色调,第二个 - 有色调,第三个 - 也没有色调,

好的。

        ImageView img1 = (ImageView) findViewById(R.id.img1);
        ImageView img2 = (ImageView) findViewById(R.id.img2);
        ImageView img3 = (ImageView) findViewById(R.id.img3);

        Drawable drawable1 = ContextCompat.getDrawable(this, R.drawable.my_vector_drawable);

        Drawable drawable2 = DrawableCompat.wrap(ContextCompat.getDrawable(this, R.drawable.my_vector_drawable));
        DrawableCompat.setTintMode(drawable2, PorterDuff.Mode.MULTIPLY);
        DrawableCompat.setTintList(drawable2, ContextCompat.getColorStateList(this, R.color.menu_tint_colors));

        Drawable drawable3 = ContextCompat.getDrawable(this, R.drawable.my_vector_drawable);

        img1.setImageDrawable(drawable1);
        img2.setImageDrawable(drawable2);
        img3.setImageDrawable(drawable3);

其中R.drawable.my_vector_drawable是白色图形。

但结果是 – 3 个带有色调的图标(为什么?!)。

例如,我尝试设置ContextCompat.getColor(this, R.color.somecolor),结果是...两个带有色调的图标!图标 2 和 3,以及第一个图标 – 无色调(为什么?!)

如何加载未缓存的可绘制对象?或者如何解决这个问题?应用程序兼容性 23.4.+

最佳答案

你必须mutate()你的绘图。

现在您引用了完全相同的来源。一旦你改变了你的可绘制对象,每个可绘制对象都会有自己的状态。

Drawable d = ContextCompat.getDrawable(this, R.drawable.my_vector_drawable).mutate();

来自docs :

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:为三个图标之一着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43043294/

相关文章:

Android裁剪坐标

java - Android Java 将颜色设置为颜色变量

android - 如何在 TabHost 中更改颜色

使用矢量 xml 作为可绘制 API 16 时的 Android ResourceNotFound

android - 每轮for循环的不同图像

java - Android:如何使用 XML 绘制 8 个相等的矩形以适合屏幕宽度

android - 更改应用程序主题后,Material Components 主题对话框按钮变得浮肿

android - 关于 android 可绘制文件夹的说明

android - 使用 path.lineTo() 时对角线看起来比直线粗

android - 三星设备上的 Shape Drawables 默认为黑色背景