我正在使用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!