Other solution using Kotlin Extensions that allows setup a different color by rating range:
Extension functions and property:
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)
}
}
}
For use it:
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)