Kotlin动态修改ProgressBar的progressDrawable渐变三色实现咨询
实现方案说明
原方案问题
你当前的思路方向是正确的,但如果createProgressBar方法没有完全匹配原XML中的环形参数、渐变类型、centerX配置,会导致最终进度条样式和原有定义不一致,比如环形粗细、内径大小、渐变分布异常。
推荐实现方式(复用现有XML配置,不易出错)
不需要重新构造整个drawable,直接修改现有drawable的渐变颜色,完全保留原有XML的所有配置,不会出现样式偏差,代码如下:
val customProgressBar = view.findViewById<ProgressBar>(R.id.progressCompensationScore) // 取出原有progressDrawable,转成LayerDrawable val progressDrawable = customProgressBar.progressDrawable as LayerDrawable // 取出环形对应的GradientDrawable,索引0对应你xml里的第一个item val gradientDrawable = (progressDrawable.getDrawable(0) as GradientDrawable) // 设置渐变颜色,顺序为startColor、centerColor、endColor gradientDrawable.colors = intArrayOf(colorEasy, colorMedium, colorHard) // 保持和xml一致的centerX=0.3配置,Y方向默认居中设0.5即可 gradientDrawable.setGradientCenter(0.3f, 0.5f) // 刷新进度条 customProgressBar.invalidate()
备选实现(完全代码构造drawable)
如果需要完全通过代码创建drawable,createProgressBar方法实现如下,需要完全匹配原XML的参数配置:
fun createProgressBar(startColor: Int, centerColor: Int, endColor: Int): Drawable { val gradientDrawable = GradientDrawable() // 设置为环形 gradientDrawable.shape = GradientDrawable.RING // 匹配原xml的参数 gradientDrawable.innerRadiusRatio = 2.15f gradientDrawable.thicknessRatio = 50.0f // 设置为扫描渐变 gradientDrawable.gradientType = GradientDrawable.SWEEP_GRADIENT // 设置三个渐变颜色 gradientDrawable.colors = intArrayOf(startColor, centerColor, endColor) // 设置渐变中心X偏移0.3 gradientDrawable.setGradientCenter(0.3f, 0.5f) // 包装成LayerDrawable,适配ProgressBar的progressDrawable要求 return LayerDrawable(arrayOf(gradientDrawable)) }
集成到现有逻辑的代码:
val customProgessBar = view.findViewById<ProgressBar>(R.id.progressCompensationScore) val draw = createProgressBar(colorEasy, colorMedium, colorHard) customProgessBar.progressDrawable = draw
注意事项
- 如果你使用的自定义CustomProgressBar内部有对progressDrawable的特殊处理,需要确认是否支持动态替换drawable,无特殊处理的话上述代码可直接运行
- 优先选择第一种复用XML配置的方案,无需额外维护XML和代码的参数一致性,修改成本更低
内容的提问来源于stack exchange,提问作者siki
相关产品推荐
相关产品推荐

