Skip to content

Instantly share code, notes, and snippets.

@KvRae
Last active July 28, 2024 14:23
Show Gist options
  • Save KvRae/f3a9b57b18d46def3082923832c6157d to your computer and use it in GitHub Desktop.
Save KvRae/f3a9b57b18d46def3082923832c6157d to your computer and use it in GitHub Desktop.
Jetpack compose customizable rating bar component that displays a series of stars to represent a rating.
/**
* A customizable rating bar component that displays a series of stars.
*
* @param maxRating The maximum number of stars to display. Defaults to 5.
* @param currentRating The number of filled stars representing the current rating. Defaults to 0.
* @param onRatingChanged A lambda function that gets called with the new rating when a star is clicked.
* It is ignored if [isClickable] is set to false.
* @param isClickable Determines if the stars are clickable or not. Defaults to true.
* @param filledIcon The icon to use for filled stars. Defaults to [Icons.Filled.Star].
* @param outlinedIcon The icon to use for empty stars. Defaults to [Icons.Outlined.Star].
* @param iconSize The size of each star icon. Defaults to 24.dp.
* @param filledColor The color of the filled stars. Defaults to the primary color of the current theme.
* @param outlinedColor The color of the empty stars. Defaults to Gray.
*/
@Composable
fun RatingBar(
maxRating: Int = 5,
currentRating: Int = 0,
onRatingChanged: (Int) -> Unit = {},
isClickable: Boolean = true,
filledIcon: ImageVector = Icons.Filled.Star,
outlinedIcon: ImageVector = Icons.Outlined.Star,
iconSize: Dp = 24.dp,
filledColor: Color = MaterialTheme.colorScheme.primary,
outlinedColor: Color = Color.Gray
) {
Row(Modifier.padding(4.dp)) {
repeat(maxRating) { index ->
val isStarFilled = index < currentRating
Icon(
imageVector = if (isStarFilled) filledIcon else outlinedIcon,
contentDescription = null,
tint = if (isStarFilled) filledColor else outlinedColor,
modifier = Modifier
.clickable(enabled = isClickable) { if (isClickable) onRatingChanged(index + 1) }
.size(iconSize)
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment