[英]How to change color of drawable set as android:background?
I have an icon which look like this: icon in my constraint layout. 我有一个看起来像这样的图标 :我的约束布局中的图标 。
This is my layout xml for this image view: 这是此图像视图的布局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" />
As you can see, the icon is just a dollar sign. 如您所见,图标只是一个美元符号。 I set that grey circle as background.
我将那个灰色圆圈设为背景。 The problem is that I need to change color of that background dynamically.
问题是我需要动态更改该背景的颜色。 The dollar sign need to stay white.
美元符号需要保持白色。 My question is, is there any way how to change only the color of background?
我的问题是,有没有办法如何只改变背景的颜色?
Another solution would be to use that circle as next imageview and then change color of that image view. 另一种解决方案是将该圆圈用作下一个图像视图,然后更改该图像视图的颜色。 But i think that there could be some more "clear solution for this issue.
但我认为对于这个问题可能会有更明确的解决方案。
Thanks for tips :) 谢谢你的提示:)
Try: 尝试:
yourImage.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
This literally gets background (without src
) from ImageView
and covers its shape with color. 这从字面上获取
ImageView
背景 (没有src
)并用颜色覆盖它的形状。 The way the drawable and given color are combining is defined by mode of Porter Duff - here you have more about it. 可绘制和给定颜色组合的方式由Porter Duff模式定义 - 在这里您可以了解更多信息。
Best way to do it: 最好的方法:
public static void colorDrawable(View view, int color) {
Drawable wrappedDrawable = DrawableCompat.wrap(view.getBackground());
if (wrappedDrawable != null) {
DrawableCompat.setTint(wrappedDrawable.mutate(), color);
setBackgroundDrawable(view, wrappedDrawable);
}
}
public static void setBackgroundDrawable(View view, Drawable drawable) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(drawable);
} else {
view.setBackground(drawable);
}
}
Well u must try 你必须尝试
android:backgroundTint="your color"
in imageview tag 在imageview标签中
this will do the work 这将完成工作
Did you try android:background="@color/my_color"
and through code imageView.setBackgroundColor(Color.rgb(255, 255, 255));
你尝试过
android:background="@color/my_color"
并通过代码imageView.setBackgroundColor(Color.rgb(255, 255, 255));
? ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.