使用Kotlin扩展的另一种解决方案,允许通过评分范围设置不同的颜色:
扩展函数和属性:
var RatingBar.colorScheme: Map<Float, Int>?
get() = getTag(R.id.rating_bar_color_scheme) as Map<Float, Int>?
set(value) = setTag(R.id.rating_bar_color_scheme, value)
fun RatingBar.setColorByRating(rating: Float) {
val colorScheme = getTag(R.id.rating_bar_color_scheme) as Map<Float, Int>
colorScheme[rating]?.also { color -> setLayerColor(2, color) }
setLayerColor(1, ContextCompat.getColor(context, android.R.color.transparent))
setLayerColor(0, ContextCompat.getColor(context, android.R.color.darker_gray))
}
fun RatingBar.setLayerColor(layerIndex: Int, color: Int) {
val drawable = progressDrawable as LayerDrawable
drawable.getDrawable(layerIndex).also {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
DrawableCompat.setTint(it, color)
} else {
it.setColorFilter(color, PorterDuff.Mode.SRC_IN)
}
}
}
使用方法:
val red = ContextCompat.getColor(requireContext(), R.color.redColor)
val yellow = ContextCompat.getColor(requireContext(), R.color.yellowColor)
val green = ContextCompat.getColor(requireContext(), R.color.greenLightColor)
rbStars?.colorScheme = mapOf(
1.0F to red,
2.0F to red,
3.0F to yellow,
4.0F to green,
5.0F to green
)
rbStars?.setColorByRating(rating)