我有一个RecyclerView,可以使用搜索输入进行过滤。 问题是,例如,如果我搜索“ ber”,它将过滤,但是如果我更改字母或删除字母,则列表不会更新。 有人可以帮忙吗?
过滤器功能代码:
@Override
public Filter getFilter()
{
return new Filter()
{
@Override
protected FilterResults performFiltering(CharSequence charSequence)
{
FilterResults results = new FilterResults();
//If there's nothing to filter on, return the original data for your list
if(charSequence == null || charSequence.length() == 0)
{
results.values = cityList;
results.count = cityList.size();
}
else
{
ArrayList<City> filteredResultsData = new ArrayList<City>();
for(City data : cityList)
{
if(data.getName().toLowerCase().startsWith(charSequence.toString().toLowerCase()))
{
filteredResultsData.add(data);
}
}
results.values = filteredResultsData;
results.count = filteredResultsData.size();
}
return results;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults)
{
cityList = (ArrayList<City>)filterResults.values;
notifyDataSetChanged();
}
};
}
收听者代码:
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
adapter.getFilter().filter(cs);
}
@Override
public void afterTextChanged(Editable s) { }
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
});
答案 0 :(得分:0)
您可以使用
if (charSequence.length() == 0) {
filteredList.addAll(contactsList);
}
这是onTextChanged()
,其中filteredList是搜索到的内容,而contactList是完整列表,它们都是对象的数组列表,就像我的情况是userdetails
这是我应用程序中的完整示例,此逻辑在两种情况下均有效,即删除和更改搜索字符
private void addSearchListener() {
mySearchText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
filteredList.clear();
charSequence = charSequence.toString().toLowerCase();
if (charSequence.length() == 0) {
filteredList.addAll(contactsList);
} else
for (int j = 0; j < contactsList.size(); j++) {
final Userdetails userdetails = contactsList.get(j);
String name = userdetails.getName();
if (name.toLowerCase().contains(charSequence.toString().toLowerCase())) {
filteredList.add(contactsList.get(j));
}
}
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
Collections.sort(filteredList, (u1, t1) -> u1.getName().compareToIgnoreCase(t1.getName()));
mfilteredAdapter = new ContactsRecylerviewAdapater(filteredList, ContactsList.this);
recyclerView.setAdapter(mfilteredAdapter);
mfilteredAdapter.notifyAdapterDataSetChanged(ContactsList.this);
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}