Skip to content

Instantly share code, notes, and snippets.

@XFY9326
Created March 25, 2022 11:59
Show Gist options
  • Save XFY9326/2067efcc3c5899557cc6a334d76a92c8 to your computer and use it in GitHub Desktop.
Save XFY9326/2067efcc3c5899557cc6a334d76a92c8 to your computer and use it in GitHub Desktop.
Jetpack Compose VerticalScrollBar for Android
// Reference: https://stackoverflow.com/questions/66341823/jetpack-compose-scrollbars/68056586#68056586
// Modify: LazyListState -> ScrollState
fun Modifier.verticalScrollbar(
scrollState: ScrollState,
scrollBarWidth: Dp = 4.dp,
minScrollBarHeight: Dp = 5.dp,
scrollBarColor: Color = Color.Blue,
cornerRadius: Dp = 2.dp
): Modifier = composed {
val targetAlpha = if (scrollState.isScrollInProgress) 1f else 0f
val duration = if (scrollState.isScrollInProgress) 150 else 500
val alpha by animateFloatAsState(
targetValue = targetAlpha,
animationSpec = tween(durationMillis = duration)
)
drawWithContent {
drawContent()
val needDrawScrollbar = scrollState.isScrollInProgress || alpha > 0.0f
if (needDrawScrollbar && scrollState.maxValue > 0) {
val visibleHeight: Float = this.size.height - scrollState.maxValue
val scrollBarHeight: Float = max(visibleHeight * (visibleHeight / this.size.height), minScrollBarHeight.toPx())
val scrollPercent: Float = scrollState.value.toFloat() / scrollState.maxValue
val scrollBarOffsetY: Float = scrollState.value + (visibleHeight - scrollBarHeight) * scrollPercent
drawRoundRect(
color = scrollBarColor,
topLeft = Offset(this.size.width - scrollBarWidth.toPx(), scrollBarOffsetY),
size = Size(scrollBarWidth.toPx(), scrollBarHeight),
alpha = alpha,
cornerRadius = CornerRadius(cornerRadius.toPx())
)
}
}
}
// Usage
@Compose
fun ScrollText() {
val scrollState = rememberScrollState()
Text(
text = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30",
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp)
.verticalScroll(scrollState)
.verticalScrollbar(scrollState)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment