动态设置渐变色背景,可以使用 GradientDrawable 实现。
GradientDrawable 可以设置多个色值 GradientDrawable.Orientation 可设置方向
private fun generateGradientDrawable(colors: String?): GradientDrawable? {
if (colors.isNullOrEmpty()) return null
try {
val colorSplits = colors.split("-")
if (colorSplits.size != 3) return null
val color1 = Color.parseColor(colorSplits.getItem(0))
val color2 = Color.parseColor(colorSplits.getItem(1))
val color3 = Color.parseColor(colorSplits.getItem(2))
val colorsArray = intArrayOf(color1, color2, color3)
return GradientDrawable().apply {
shape = GradientDrawable.RECTANGLE
setColors(colorsArray)
gradientType = GradientDrawable.LINEAR_GRADIENT
}
} catch (e: Exception) {
return null
}
}