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)
            }
        }
    }
}

Kotlin相关问答推荐

某些公共函数显然不能在类实例上访问;Klaxon示例

Microronaut Data 4和JDbi

相当于roomdb中的DateTime Bigint列的是什么

为什么不';Kotlin是否在数据类构造函数中隐式分配null值可为null的字段?

如何将消费者放入 Kotlin 的 map 中?

在 Kotlin 中将两个字节转换为 UIn16

为什么 Kotlin 在将协变类型参数转换为不变类型参数时会产生 Unchecked Cast 警告?

如何将光标从一个文本字段传递到 Jetpack Compose 中的其他文本字段?

为什么这个 Kotlin 代码不起作用? (如果 str[index] 在列表中,则打印)

有没有一种简单的方法可以将数组/列表中的每个元素相互相乘 - Kotlin?

Kotlin 代码是如何编译成原生代码的?

对列表中数字的子集求和

使用 Hilt 注入 CoroutineWorker

Kotlin 创建snackbar

作为 Kotlin 中的函数的结果,如何从 Firestore 数据库返回列表?

如何获取Kotlin中变量的名称?

在 Kotlin 中创建 Spinner 时,如何在 Fragment 中的旋转屏幕上修复指定为非空的参数为空?

Kotlin数据类打包

内联 Kotlin 方法没有覆盖报告

目前不支持 Gradle 项目的自动库版本更新.请手动更新您的 build.gradle