如何更改代码 (Java/Kotlin) 文件中的可绘制背景颜色



我创建了以下可绘制对象,并将其设置为代码中的按钮背景。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="8dp"/>
<solid android:color="@color/background_profile"/>
<padding android:left="8dp" android:top="7dp" android:right="8dp" android:bottom="6dp" />
</shape>

科特林文件

btn?.background= resources?.getDrawable(R.drawable.drawable_rewards)

现在我将从我的服务中获取颜色,就像这个"#00000"一样,我需要更新drawable_rewards.xml文件中的颜色。

有什么方法可以动态更改可绘制文件的颜色。

val wrappedDrawable: Drawable = DrawableCompat.wrap(ContextCompat.getDrawable(context!!, R.drawable.drawable_rewards)!!)
DrawableCompat.setTint(wrappedDrawable, ContextCompat.getColor(context!!, R.color.colorPrimary))
btn?.background = wrappedDrawable

答案是您将获得按钮的背景作为可绘制对象 ->更改可绘制对象的颜色 ->将可绘制对象设置为按钮的背景

val drawable: Drawable = buttonChange.background
drawable.setColorFilter(Color.GREEN, PorterDuff.Mode.SRC)
buttonChange.background = drawable
fun View.setBgColor(color: String?) {
val bgColor = parseColor(color) ?: return
val drawable = if (background is InsetDrawable)
(background as InsetDrawable).drawable
else
background
when (drawable?.mutate()) { //mutate before change is important
is ShapeDrawable -> (drawable as ShapeDrawable).paint.color = bgColor
is GradientDrawable -> (drawable as GradientDrawable).setColor(bgColor)
is ColorDrawable -> (drawable as ColorDrawable).color = bgColor
}
}
fun parseColor(color: String?): Int? {
return try {
Color.parseColor(color)
} catch (e: Exception) {
null
}
}

最新更新