如何在Kotlin中动态修改Drawable的solid与stroke标签颜色
动态修改RippleDrawable内Shape的填充与描边颜色
想单独改<solid>和<stroke>的颜色,得逐层拿到对应的Drawable对象来操作,具体步骤如下:
1. 解析背景Drawable
先从ImageButton拿到背景,再层层拆出里面的ShapeDrawable:
val button = findViewById<ImageButton>(R.id.button_dnd) // 背景是RippleDrawable,强转类型 val rippleDrawable = button.background as RippleDrawable // 通过item的id获取内部Shape对应的GradientDrawable val shapeDrawable = rippleDrawable.findDrawableByLayerId(R.id.circle_border) as GradientDrawable
2. 修改填充色(对应标签)
直接调用setColor()就能修改填充色:
// 替换为你需要的颜色,用ContextCompat兼容低版本系统 shapeDrawable.setColor(ContextCompat.getColor(this, R.color.your_solid_color))
3. 修改描边色(对应标签)
使用setStroke()方法,需要传入描边宽度(可保留原宽度)和新颜色:
// 获取原描边宽度,避免修改后改变按钮粗细 val strokeWidth = shapeDrawable.strokeWidth // 设置新的描边颜色 shapeDrawable.setStroke(strokeWidth, ContextCompat.getColor(this, R.color.your_stroke_color))
完整代码示例
val button = findViewById<ImageButton>(R.id.button_dnd) val rippleDrawable = button.background as RippleDrawable val shapeDrawable = rippleDrawable.findDrawableByLayerId(R.id.circle_border) as GradientDrawable // 修改填充色 shapeDrawable.setColor(ContextCompat.getColor(this, R.color.new_solid_color)) // 修改描边色,保留原宽度 val originalStrokeWidth = shapeDrawable.strokeWidth shapeDrawable.setStroke(originalStrokeWidth, ContextCompat.getColor(this, R.color.new_stroke_color))
注意事项
- 必须确保round_button.xml里的
<item>设置了android:id="@+id/circle_border",否则findDrawableByLayerId会返回null - XML中的
<shape>对应Android的GradientDrawable,即使是纯色填充也需要强制转换为该类型 - 如果在Fragment中使用,
ContextCompat.getColor()的第一个参数替换为requireContext()即可
内容的提问来源于stack exchange,提问作者Goutham
相关产品推荐
相关产品推荐

