如何更改可绘制设置为android:background的颜色?

Jos*_*ška 3 android imageview android-layout android-drawable

我有一个看起来像这样的图标:我的约束布局中的图标

这是此图像视图的布局XML:

<ImageView
        android:id="@+id/vTotalPaidAvatar"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:contentDescription="@null"
        android:src="@drawable/ic_group_ic_total"
        tools:src="@drawable/ic_group_ic_total"
        app:layout_constraintLeft_toLeftOf="@+id/vSettleDebtsLayout"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        app:layout_constraintTop_toTopOf="@+id/vSettleDebtsLayout"
        android:layout_marginTop="16dp"
        android:background="@drawable/avatar_circle" />
Run Code Online (Sandbox Code Playgroud)

如您所见,该图标只是一个美元符号。我将那个灰色圆圈设置为背景。问题是我需要动态更改该背景的颜色。美元符号需要保持白色。我的问题是,有什么办法只能改变背景颜色吗?

另一个解决方案是使用该圆圈作为下一个图像视图,然后更改该图像视图的颜色。但是我认为对于这个问题可能会有更多“明确的解决方案。

感谢提示:)

pau*_*lab 6

尝试:

yourImage.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
Run Code Online (Sandbox Code Playgroud)

从字面上获取背景(无src),ImageView并用颜色覆盖其形状。可绘制的颜色和给定的颜色组合的方式由Porter Duff的模式定义- 在这里您可以了解更多。