【问题标题】:Firebase UI: How to add new message to the top of recycleViewFirebase UI:如何将新消息添加到 recyclerView 的顶部
【发布时间】:2018-12-20 22:03:06
【问题描述】:

我正在使用 Firebase 回收适配器来显示我的消息。我想在回收视图顶部显示新收到的消息。 例如,Jfi.. 新发送/接收的消息应该在顶部。

这是我的数据库结构。

代码:

    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    Query query = rootRef.child("messages").child(messageSenderId).child(messageReceiverId);


    FirebaseRecyclerOptions<ChatMessage> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<ChatMessage>()
            .setQuery(query, ChatMessage.class)
            .build();

谢谢

【问题讨论】:

    标签: android firebase firebase-realtime-database android-recyclerview firebaseui


    【解决方案1】:

    您可以将带有时间戳的消息存储到 Firebase 中,然后当您检索消息的所有数据时,将其与其余消息进行比较并按日期排序,它们将在顶部显示最新的消息,或者只是反转RecyclerView,您将在RecyclerView顶部看到最新消息

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setReverseLayout(true);
    linearLayoutManager.setStackFromEnd(true);
    myRecyclerView.setLayoutManager(linearLayoutManager);
    

    编辑

    您可以比较每条消息的值并按照从 Firebase 获得的时间戳对其进行排序

     public class timeStampSort implements Comparator<YourModel> {
    
            @Override
            public int compare(YourModel o1, YourModel o2) {
                return Long.compare(o2.getTimestamp(), o1.getTimestamp());
    
            }
    
        }
    

    然后在调用mAdapter = new MessagesAdapter.... 之前执行此操作

    Collections.sort(yourArray, new timeStampSort());
    

    这应该使用每个消息的时间戳来排序您的消息,而不必反转RecyclerView

    如果您已经在查询中创建了另一个 orderByChild 并且您不能多次执行上述排序,则可以进行上述排序。

    但是,正如弗兰克所说,使用orderByChild 会更有效,所以你只能这样做

    Query query = rootRef.child("messages").child(messageSenderId).child(messageReceiverId).orderByChild("timestamp");
    

    【讨论】:

    • 我试过 linearLayoutManager.setStackFromEnd(true);但它没有用。时间戳听起来不错:)
    • 是的,推送带有时间戳的消息然后可以通过 collection.sort 检索和排序,使用 ServerValue.TIMESTAMP
    • 太棒了。让我检查一下。
    • Firebase 数据库查询始终是升序的。因此,如果您希望最新的节点位于顶部,您将需要存储例如倒置的时间戳和顺序。例如。 nodeRef.child("invertedTimestamp").setValue(0 - System.currentTimeMillis())stackoverflow.com/questions/44442816/…。幸运的是,Android 可以很容易地在 UI 中进行反转,我完全忘记了,但幸运的是 Gastón 没有。 ;-) 有关这些的更多信息,请参阅stackoverflow.com/search?q=%5Bfirebaseui%5D+reverse
    猜你喜欢
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多