A visual and interactive scrollbar that represents the current scroll position of a scrolling component and allows users to scroll the component by dragging the thumb or pressing the track.
@Sampled
@Composable
fun InteractiveScrollbarWithLazyColumnSample() {
val state = rememberLazyListState()
val coroutineScope = rememberCoroutineScope()
val scrollIndicatorState = state.scrollIndicatorState
val scrollToPositionFraction: suspend (Float) -> Unit = { positionFraction ->
if (scrollIndicatorState != null) {
val maxScrollOffset =
scrollIndicatorState.contentSize - scrollIndicatorState.viewportSize
val targetPx = positionFraction * maxScrollOffset
val deltaPx = targetPx - scrollIndicatorState.scrollOffset
state.scrollBy(deltaPx)
}
}
val scrollbarModifier =
if (scrollIndicatorState != null) {
Modifier.interactiveScrollbar(
state = scrollIndicatorState,
orientation = Orientation.Vertical,
onThumbDrag = { coroutineScope.launch { scrollToPositionFraction(it) } },
onTrackPress = { coroutineScope.launch { scrollToPositionFraction(it) } },
)
} else {
Modifier
}
LazyColumn(state = state, modifier = scrollbarModifier) {
items(100) { index ->
Text(
text = "Item $index",
modifier = Modifier.fillMaxWidth().height(50.dp).wrapContentSize(Alignment.Center),
)
}
}
}
@Sampled
@Composable
fun InteractiveScrollbarWithVerticalScrollSample() {
val state = rememberScrollState()
val coroutineScope = rememberCoroutineScope()
val scrollIndicatorState = state.scrollIndicatorState
val scrollToPositionFraction: suspend (Float) -> Unit = { positionFraction ->
if (scrollIndicatorState != null) {
val maxScrollOffset =
scrollIndicatorState.contentSize - scrollIndicatorState.viewportSize
val targetPx = (positionFraction * maxScrollOffset).roundToInt()
state.scrollTo(targetPx)
}
}
val scrollbarModifier =
if (scrollIndicatorState != null) {
Modifier.interactiveScrollbar(
state = scrollIndicatorState,
orientation = Orientation.Vertical,
onThumbDrag = { coroutineScope.launch { scrollToPositionFraction(it) } },
onTrackPress = { coroutineScope.launch { scrollToPositionFraction(it) } },
)
} else {
Modifier
}
Column(
// Chain before verticalScroll so the scrollbar doesn't scroll with content.
modifier = scrollbarModifier.verticalScroll(state)
) {
repeat(100) { index ->
Text(
text = "Item $index",
modifier = Modifier.fillMaxWidth().height(50.dp).wrapContentSize(Alignment.Center),
)
}
}
}