【问题标题】:How to put the last document added to the bottom of recyclerview?如何将最后添加的文档放在recyclerview的底部?
【发布时间】:2018-12-29 23:10:19
【问题描述】:

基本上我想将消息对齐,因为它们应该在通常的聊天应用程序中。

现在消息在RecyclerView 中正确对齐。但是每当我发送新消息时,它都会将它们放在其他消息的顶部。每当我返回并再次访问该活动时,消息都会得到妥善安排(即使是最重要的)。

我只想让我发送的消息显示在底部。任何帮助将不胜感激

mLinearLayout.setReverseLayout(true);

然后:

private void loadmessage() {
mFirestore.collection("Users").orderBy("Timestamp", Query.Direction.DESCENDING).limit(10).addSnapshotListener(new EventListener<QuerySnapshot>() {
    @Override
    public void onEvent(@Nullable QuerySnapshot snapshots,
                        @Nullable FirebaseFirestoreException e) {
        if (e != null) {
            Log.w("TAG", "listen:error", e);
            return;
        }

        for (DocumentChange dc : snapshots.getDocumentChanges()) {
            switch (dc.getType()) {
                case ADDED:
                    Message message = dc.getDocument().toObject(Message.class);
                    messageList.add(message);
                    mAdapter.notifyDataSetChanged();
                    mMessagesList.scrollToPosition(messageList.size()-10);
                    break;
            }
        }
    }
});

}

【问题讨论】:

  • 你在用listview来显示消息吗?
  • 我正在使用 RecyclerView 来显示消息。
  • mLinearLayout.setReverseLayout(true) 这将反转适配器内容。你想要吗?
  • 是的。反转 recyclerView 将以所需的顺序(从旧到新)显示聊天。

标签: java android firebase android-recyclerview google-cloud-firestore


【解决方案1】:

要解决这个问题,您需要像这样更改查询:

mFirestore.collection("Users")
    .orderBy("Timestamp", Query.Direction.DESCENDING)
    .limit(10)
    .addSnapshotListener(/* ... */);

你的RecyclerView 应该是这样的:

LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);

此方法将根据需要反转您的顺序。

编辑:

您可以使用 getItem() 方法来反转项目查找,如下所示:

@Override
public HashMap getItem(int pos) {
    return super.getItem(getCount() - 1 - pos);
}

【讨论】:

  • 是的,但它只会给出前 10 个文档,而不是最后 10 个文档。
  • 哦,对不起。应该是DESCENDING,就像我更新的答案一样,而不是ASCENDING。现在可以用了吗?
  • 我已经在使用DESCENDING。但是由于布局颠倒了,每当我发送新消息时,它都会将它们放在顶部而不是底部。
  • 这是新事物。 getItem() 方法在哪里?
  • 您需要在适配器类中覆盖它。
【解决方案2】:

Here 是相同的情况,它也有答案。所以万一有人在寻找答案。亚历克斯已经说明了解决这种情况的各种方法。

This 是 Firestore 聊天应用功能的 github 存储库。

【讨论】:

    【解决方案3】:

    试试这个……

     recyclerView.scrollToPosition(messageList.size()-1);
     mAdapter.notifyDataSetChanged();
    

    【讨论】:

    • 同样的结果。只是它现在不会滚动到底部。
    • 每当您添加新消息时,请调用这些行。它将在底部显示底部的新消息..
    • 我最近在 listView...
    • 它仍然在顶部显示新添加的消息。我正在使用mLinearLayout.setReverseLayout(true);。你知道吗?
    • mLinearLayout.setReverseLayout(true);删除此行然后尝试我的代码
    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 2023-03-24
    相关资源
    最近更新 更多