【问题标题】:jetpack compose LazyColumn scroll not workjetpack compose LazyColumn 滚动不起作用
【发布时间】:2022-03-04 16:25:25
【问题描述】:

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

聊天消息使用 LazyColumn 显示。 消息来自 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)
            )
        }
    }
}

但是上面的代码不起作用.. 我检查了它显示的 logcat...:

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!

【问题讨论】:

    标签: android android-jetpack-compose


    【解决方案1】:

    我认为您在渲染 LazyColumn 时尝试滚动。

    我也认为你需要再减去一个,因为索引从 0 开始?

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

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

    【讨论】:

      猜你喜欢
      • 2022-07-29
      • 2021-08-13
      • 2021-09-28
      • 1970-01-01
      • 2021-06-01
      • 2022-11-10
      • 1970-01-01
      • 2021-11-26
      • 2021-03-11
      相关资源
      最近更新 更多