代码之家  ›  专栏  ›  技术社区  ›  dev.farmer

jetpack compose LazyColumn滚动条不工作

  •  1
  • dev.farmer  · 技术社区  · 4 年前

    我正在使用jetpack compose开发一个android聊天应用程序。

    聊天信息使用Lazy列显示。 这些信息来自WebSocket。

    我想发展的是:

    • 如果用户在收到新消息时看到最新消息,LazyColumn应该滚动到最新消息。
    • 如果用户在收到新消息时看到上一条消息(滚动到上方),则不应更改滚动位置。

    为了做到这一点,我发现 listState.layoutInfo.visibleItemsInfo . 如果 listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index == chatMessages.size - 1 表示用户正在看到最新消息。(位于底部)

    LazyColumn(
        state = listState
    ) {
        vm.scrollToBottom.value = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index == chatMessages.size - 1
        Log.d("TEST", "[test] scrollToBottom: ${vm.scrollToBottom.value}")
        if (vm.scrollToBottom.value) {
            coroutineScope.launch {
                Log.d("TEST", "[test] scroll!")
                listState.animateScrollToItem(chatMessages.size)
            }
        }
        itemsIndexed(chatMessages) { _, chat ->
            when (chat.command) {
                Command.MESSAGE -> when (chat.userId) {
                    myId -> MyChat(chat = chat)
                    else -> OtherUserChat(chatMsg = chat)
                }
                Command.JOIN -> JoinLeaveMessage(
                    chat = chat,
                    message = stringResource(R.string.user_joined_group)
                )
                Command.LEAVE -> JoinLeaveMessage(
                    chat = chat,
                    message = stringResource(R.string.user_left_group)
                )
            }
        }
    }
    

    但是上面的代码不起作用。。 我查了一下它显示的日志

    2022-03-04 12:17:40.534 19854-19854 D/TEST: [test] scrollToBottom: true
    2022-03-04 12:17:40.549 19854-19854 D/TEST: [test] scroll!
    2022-03-04 12:17:40.551 19854-19854 D/TEST: [test] scrollToBottom: true
    2022-03-04 12:17:40.566 19854-19854 D/TEST: [test] scroll!
    ...
    2022-03-04 12:17:40.635 19854-19854 D/TEST: [test] scrollToBottom: true
    2022-03-04 12:17:40.649 19854-19854 D/TEST: [test] scroll!
    2022-03-04 12:17:40.651 19854-19854 D/TEST: [test] scrollToBottom: true
    2022-03-04 12:17:40.665 19854-19854 D/TEST: [test] scroll!
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   Anders Ullnæss    4 年前

    我想你是想在LazyColumn被渲染时滚动。

    我还认为你需要再减去一个,因为指数从0开始?

    您可以尝试在LauncheFect中这样做:

    val composableScope = rememberCoroutineScope()
    val scrollToBottom = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index == chatMessages.size - 2
    val lastItemIndex = chatMessages.size - 1
    
    LaunchedEffect(scrollToBottom, lastItemIndex) {
        if (scrollToBottom) {
            composableScope.launch {
                listState.animateScrollToItem(lastItemIndex)
            }
        }
    }