I want to dynamically enable and disable scrolling programmatically in a LazyColumn
.
There don't seem to be any relevant functions on LazyListState
or relevant parameters on LazyColumn
itself. How can I achieve this in Compose?
I want to dynamically enable and disable scrolling programmatically in a LazyColumn
.
There don't seem to be any relevant functions on LazyListState
or relevant parameters on LazyColumn
itself. How can I achieve this in Compose?
There's not (currently) a built-in way to do this, which is a reasonable feature request.
However, the scroll
API is flexible enough that we can add it ourselves. Basically, we create a never-ending fake scroll at MutatePriority.PreventUserInput
to prevent scrolling, and then use a do-nothing scroll at the same priority to cancel the first "scroll" and re-enable scrolling.
下面是LazyListState
上的两个实用功能,用于禁用/重新启用滚动,以及它们的一个演示(需要一些导入,但Android Studio应该为您提供建议).
Note that because we're taking control of scrolling to do this, calling reenableScrolling
will also cancel any ongoing scrolls or flings (that is, you should only call it when scrolling is disabled and you want to re-enable it, not just to confirm that it's enabled).
fun LazyListState.disableScrolling(scope: CoroutineScope) {
scope.launch {
scroll(scrollPriority = MutatePriority.PreventUserInput) {
// Await indefinitely, blocking scrolls
awaitCancellation()
}
}
}
fun LazyListState.reenableScrolling(scope: CoroutineScope) {
scope.launch {
scroll(scrollPriority = MutatePriority.PreventUserInput) {
// Do nothing, just cancel the previous indefinite "scroll"
}
}
}
@Composable
fun StopScrollDemo() {
val scope = rememberCoroutineScope()
val state = rememberLazyListState()
Column {
Row {
Button(onClick = { state.disableScrolling(scope) }) { Text("Disable") }
Button(onClick = { state.reenableScrolling(scope) }) { Text("Re-enable") }
}
LazyColumn(Modifier.fillMaxWidth(), state = state) {
items((1..100).toList()) {
Text("$it", fontSize = 24.sp)
}
}
}
}