Android/Compose
[compose] RatingBar 만들기
sryang
2024. 7. 28. 18:25
compose 에서는 RatingBar를 따로 제공하지 않는다.
기존 widget과 호환
Compose의 기능중에는 기존 widget을 불러올 수 있는 기능이 있다.
Compose의 AndroidView를 사용하면 가능하다.
ratingbar의 색상을 바꾸는것을 찾는데 오랜시간이 걸렸다.
@Composable
internal fun AndroidViewRatingBar(
modifier: Modifier = Modifier,
rating: Float,
isSmall: Boolean = false,
changable: Boolean = true,
progressTintColor: Color? = null
) {
// Adds view to Compose
AndroidView(
modifier = modifier,
factory = { context ->
// Creates view
if (isSmall) {
RatingBar(context, null, android.R.attr.ratingBarStyleSmall).apply {
// Sets up listeners for View -> Compose communication
this.rating = rating
setIsIndicator(!changable)
progressTintColor?.let {
progressTintList = ColorStateList(
arrayOf(
intArrayOf(android.R.attr.state_enabled), // enabled
), intArrayOf(
it.hashCode(),
)
)
secondaryProgressTintList = ColorStateList(
arrayOf(
intArrayOf(android.R.attr.state_enabled), // enabled
), intArrayOf(
it.hashCode(),
)
)
}
}
} else {
RatingBar(context).apply {
// Sets up listeners for View -> Compose communication
this.rating = rating
setIsIndicator(!changable)
progressTintColor?.let {
progressTintList = ColorStateList(
arrayOf(
intArrayOf(android.R.attr.state_enabled), // enabled
), intArrayOf(
it.hashCode(),
)
)
secondaryProgressTintList = ColorStateList(
arrayOf(
intArrayOf(android.R.attr.state_enabled), // enabled
), intArrayOf(
it.hashCode(),
)
)
}
}
}
},
update = { view ->
// View's been inflated or state read in this block has been updated
// Add logic here if necessary
// As selectedItem is read here, AndroidView will recompose
// whenever the state changes
// Example of Compose -> View communication
}
)
}
@Preview
@Composable
fun PreviewAndroidViewRatingBar() {
AndroidViewRatingBar(
Modifier,
3.5f,
isSmall = false,
changable = true,
progressTintColor = Color.Yellow
)
}