所以我正在测试Recycler View,在添加新项目时遇到了一些问题。
我有一个RecyclerView,我试图在其中显示用户的联系人,但当我创建一个新的elemen时,所有联系人都会重复。我知道在添加新数据之前应该清理视图,但我不知道该怎么做。
这是我的主要活动代码
for (DataSnapshot postSnapshot : snapshot.child(currentUser.getUid()).getChildren()) {
Document document = postSnapshot.getValue(Document.class);
mDocuments.add(document);
}
adapter = new ContactAdapter(getApplicationContext(), mContacts, mAuth);
recyclerView.setAdapter(adapter);
这是适配器
@Override
public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
Contact contactCurrent = mContacts.get(position);
holder.contactName.setText("Name: " + contactCurrent.getName());
holder.contactPhone.setText("Phone number: " + contactCurrent.getPhone());
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
public TextView contactName, contactPhone;
public ImageButton deleteContact;
public ContactViewHolder(@NonNull View itemView) {
super(itemView);
contactName = itemView.findViewById(R.id.contact_name);
contactPhone = itemView.findViewById(R.id.contact_phone);
deleteContact = itemView.findViewById(R.id.delete_contact);
}
}
哦,在向mDocuments
添加数据之前,只需使用mDocuments.clear();
。请参阅以下代码。
for (DataSnapshot postSnapshot : snapshot.child(currentUser.getUid()).getChildren()) {
mDocuments.clear();
Document document = postSnapshot.getValue(Document.class);
mDocuments.add(document);
}
adapter = new ContactAdapter(getApplicationContext(), mContacts, mAuth);
recyclerView.setAdapter(adapter);