【发布时间】: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