撰写nestedScrollConnection 不会被动画滚动触发

Mar*_*arc 5 android kotlin android-jetpack-compose android-jetpack-compose-material3 android-jetpack-compose-lazy-column

我使用 NestedScrollConnection 在 Compose 中创建了一个可折叠标头。一切都很完美,但必须添加一个内容:自动滚动到某个项目。我遇到的问题是,标题(使用 NestedScrollConnection 连接)在触发 animateScrollTo 时不会更新。

从 Android 开发人员文档中找到了类似的版本(这是来自实验性的 Material3 库,但也可能没有):

val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
Scaffold(
    modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
    topBar = {
        MediumTopAppBar(
            title = { Text("Medium TopAppBar") },
            navigationIcon = {
                Icon(imageVector = Icons.Filled.Menu, contentDescription = "Localized description")
            },
            scrollBehavior = scrollBehavior
        )
    },
    content = { innerPadding ->
        val listState = rememberLazyListState()

        val coroutines = rememberCoroutineScope()
        LaunchedEffect(key1 = Unit, block = {
            coroutines.launch {
                delay(5000)
                // Starts the scrollTo
                listState.animateScrollToItem(50, 0)
            }
        })

        LazyColumn(
            state = listState,
            contentPadding = innerPadding,
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            val list = (0..75).map { it.toString() }
            items(count = list.size) {
                Text(
                    text = list[it],
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }
)
Run Code Online (Sandbox Code Playgroud)

即使滚动到某个项目有效并且该项目可见,标题也根本没有更新。

当查看LazyListState animateScrollToItem的文档时,它没有说明任何有关跳过嵌套滚动连接的信息(如dispatchRawDelta 所做的那样)。即使使用上面的链接示例,scrollTo 项也不会更新标题状态。正常的可滚动列、LazyGrid 等也会出现此问题。

我确实想到了其他解决方法:

  • 获取滚动的像素量并将其分派到nestedScrollConnection,但没有可靠的方法从 LazyColumn 获取滚动的像素
  • 测量所有项目并通过该项目,但是当项目失效时,这将失败

我感觉这种联系的一部分缺失了。有人有什么想法吗?