更新时间:2023-01-09 21:30:28
您需要将filter()
方法从Activity
移到Adapter
.在您的适配器上添加一个其他变量,以保存未过滤的数据集的副本.在您的情况下,您需要contactsList
和copyOfContactsList
变量.
You need to move your filter()
method from your Activity
to your Adapter
. At your Adapter add one additional variable to hold a copy of unfiltered dataset. In your case, you need contactsList
and copyOfContactsList
variables.
按如下所示更改适配器的构造函数:
Change your Adapter's constructor as follows:
public class ContactsAdapter extends RecyclerView.Adapter<ContactViewHolder> {
....
private ArrayList<Contact> contactsList = new ArrayList<>();
private ArrayList<Contact> copyOfContactsList = new ArrayList<>();
....
public ContactsAdapter(Context context, ArrayList<Contact> dataSet, boolean fromMyContacts){
...
this.contactsList = dataSet;
copyOfContactsList.addAll(dataSet);
...
}
,这是要添加到Adapter
的过滤器方法:
and this is the filter method to be added to your Adapter
:
public void filter(String text) {
if(text.isEmpty()){
contactsList.clear();
contactsList.addAll(copyOfContactsList);
} else{
ArrayList<Contact> result = new ArrayList<>();
text = text.toLowerCase();
for(Contact item: copyOfContactsList){
if(item.getName().toLowerCase().contains(text)){
result.add(item);
}
}
contactsList.clear();
contactsList.addAll(result);
}
notifyDataSetChanged();
}