I want to search through RecyclerView
, I have List
(BaseOfCards is my getter&setter class)
My RecyclerViewAdapter<
Using an autocompletetextview or an edittext i handled this one as following where
public List mItems
is the initial listitem instance and .
public static List filteredIt
is the instance used in displaying items.Since the 1st time the filter results is not null the mItems
instance will be equal to the filteredIt
instance (thus loosing the initial list) then on the publishResults
method right before mItems
looses the original values, I'm equating it to the passed instance originallist
. Hope it helps someone
private static class ProductsFilter extends Filter {
private final SalesProductsAdapter adapter;
private final List originalList;
private final List filteredList;
private ProductsFilter(SalesProductsAdapter adapter, List originalList) {
super();
this.adapter = adapter;
this.originalList = new LinkedList<>(originalList);
this.filteredList = new ArrayList<>();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
filteredList.clear();
final FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0)
filteredList.addAll(originalList);
else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final SalesProductsItems it : originalList) {
if (it.getProduct().toLowerCase().contains(filterPattern)) {
filteredList.add(it);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapter.mItems = originalList;
if(results.count > 0) {
filteredIt.clear();
filteredIt.addAll((ArrayList) results.values);
adapter.notifyDataSetChanged();
} else {
filteredIt.clear();
filteredIt.addAll(adapter.mItems);
adapter.notifyDataSetChanged();
}
}
}