在RecyclerView的顶部添加新项目

时间:2018-06-27 13:38:39

标签: android android-recyclerview google-cloud-firestore android-adapter recycler-adapter

我在博客应用程序中添加了评论功能。我通过 RecyclerView 检索评论,并将orderBy("timestamp")作为新评论显示在顶部。

检索所有评论后,我使用Firebase Firestore。 用户发布新评论时,我希望评论显示在顶部。但通常,注释会添加到列表底部,因此基本上显示在recyclerview的底部。

我使用下面的代码显示了新评论顶部,但不幸的是,所有评论都转到Else语句,而不是新评论:

if (isFirstLoad) {
    userList.add(userInfo);
    commentList.add(commentInfo);
}else{
    userList.add(0, userInfo);
    commentList.add(0, commentInfo);
}

获取评论的完整代码:

Query query = db.collection("BlogPosts/" + postId + "/Comments").orderBy("timestamp", Query.Direction.DESCENDING);
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
    @Override
    public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {

        if (queryDocumentSnapshots!=null && !queryDocumentSnapshots.isEmpty()){

            for (DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()){
                if (doc.getType() == DocumentChange.Type.ADDED){

                    final BlogCommentInfo commentInfo = doc.getDocument().toObject(BlogCommentInfo.class);

                    String BlogUserId = doc.getDocument().getString("user_id");
                    db.collection("Users").document(BlogUserId).get().addOnCompleteListener(CommentActivity.this, new OnCompleteListener<DocumentSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                            if (task.isSuccessful()){

                                UsersInfo userInfo = task.getResult().toObject(UsersInfo.class);

                                if (isFirstLoad) {
                                    userList.add(userInfo);
                                    commentList.add(commentInfo);
                                }else{
                                    userList.add(0, userInfo);
                                    commentList.add(0, commentInfo);
                                }
                                adapter.notifyDataSetChanged();

                            }else{
                                Toast.makeText(CommentActivity.this, "Error: "+task.getException(), Toast.LENGTH_LONG).show();
                            }
                        }
                    });


                }
            }

        }
        isFirstLoad = false;
    }
});

请帮助我解决此问题。

或者让我知道您是否还有其他方式可以在recyclerview的顶部显示新的评论。

1 个答案:

答案 0 :(得分:0)

按命中顺序按时间戳查询:

从-

更改查询
  

查询查询= db.collection(“ BlogPosts /” + postId +   “ /Comments").orderBy("timestamp”,Query.Direction.DESCENDING);

TO-

  

查询查询= db.collection(“ BlogPosts /” + postId +   “ /Comments").orderBy("timestamp”,Query.Direction.ASCENDING);

或撤消您的评论列表