簡體   English   中英

在RecyclerView的頂部添加新項目

[英]Add new item top on RecyclerView

我在博客應用程序中添加了評論功能。 我通過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的頂部顯示新的評論。

只需按升序查詢查詢時間戳:

從以下更改查詢

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

至-

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

或撤消您的評論列表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM