Issue
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?
Solution
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.
Here are two utility functions on LazyListState
to disable/re-enable scrolling, and a demo of them both in action (some imports will be required, but Android Studio should suggest them for you).
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)
}
}
}
}
Answered By - Ryan M
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.