首页 > 解决方案 > 如何根据进度百分比设置垂直进度条颜色?

问题描述

有什么解决方案如何根据进度百分比放置进度条颜色吗?例如,如果我的progressBar 0-5% 它是红色的,如果它是5-50% 它是黄色的。如果它是 50-100%,它是绿色的。

标签: androidkotlin

解决方案


当您设置进度时,您还可以设置它的颜色。对于 API 21+;

val progress = (0..100).random()
progressBar.apply {
    this.progress = progress
    progressTintList = ColorStateList.valueOf(
        when {
            progress <= 5 -> Color.RED
            progress in 6..50 -> Color.YELLOW
            else -> Color.GREEN
        }
    )
}

根据最大进度 14 和当前进度 7 进行编辑

val maxProgress = 14
val currentProgress = 7
val fixedProgress = (100.0 / maxProgress * currentProgress).roundToInt()
progressBar.apply {
    max = maxProgress
    progress = currentProgress
    progressTintList = ColorStateList.valueOf(
        when {
            fixedProgress <= 5 -> Color.RED
            fixedProgress in 6..50 -> Color.YELLOW
            else -> Color.GREEN
        }
    )
}

推荐阅读