我正在尝试更新评论列表,并且通过使用notifyItemInserted
和notifyItemRemoved
来进行更新。当用户添加评论时,评论会完美地添加到列表中,但是当我要删除评论时会出现问题。我遇到的问题是,当我删除列表中的注释时,它不仅会立即删除注释,还会重新排列列表,并且仅当我退出活动然后重新输入时才删除注释。
有人可以告诉我如何调整代码,以便立即删除注释吗?
CommentsActivity
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);
}
}
具有存储项键的列表
public class CommentsActivity extends AppCompatActivity {
private CommentAdapter mCommentAdapter;
private List<Comment> mCommentList;
//add this
private List<String> keysList = new ArrayList<String>();
private RecyclerView mRecyclerView;
............
在添加评论的同时添加密钥:
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
Comment comment = dataSnapshot.getValue(Comment.class);
mCommentList.add(comment);
//add this
keysList.add(dataSnapshot.getKey());
mCommentAdapter.notifyItemInserted(mCommentList.size() - 1);
}
现在删除时:
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
int index = keysList.indexOf(dataSnapshot.getKey());
mCommentList.remove(index);
keysList.remove(index);
}