I am trying to update a comments list and I am doing so by using notifyItemInserted
and notifyItemRemoved
. When a user adds a comment, the comment is added to the list flawlessly, but the issue arises when I want to remove the comment. The issue that I am experiencing is that when I delete the comment in the list it doesn't just remove the comment right away, it rearranges the list, and the comment is only removed when I exit the activity and then re-enter.
有人可以告诉我如何调整代码,以便立即删除注释吗?
活动
public class CommentsActivity extends AppCompatActivity {
private CommentAdapter mCommentAdapter;
private List<Comment> mCommentList;
private RecyclerView mRecyclerView;
FirebaseUser mFirebaseUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mCommentList = new ArrayList<>();
mCommentAdapter = new CommentAdapter(this, mCommentList, mPostId);
mRecyclerView.setAdapter(mCommentAdapter);
mAddComment = findViewById(R.id.add_comment);
mImageProfile = findViewById(R.id.image_profile);
mPost = findViewById(R.id.post_comment);
getImage();
readComments();
}
private void readComments() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Comments").child(mPostId);
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
Comment comment = dataSnapshot.getValue(Comment.class);
mCommentList.add(comment);
mCommentAdapter.notifyItemInserted(mCommentList.size() - 1);
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
Comment comment = dataSnapshot.getValue(Comment.class);
int position = mCommentList.indexOf(comment);
mCommentList.remove(comment);
mCommentAdapter.notifyItemRemoved(position);
mCommentAdapter.notifyItemRangeChanged(position, mCommentList.size());
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
reference.addChildEventListener(childEventListener);
}
}
有一个存储项目密钥的列表
在添加注释的同时添加密钥:
现在,当您删除时: