Search through RecyclerView using Searchview

前端 未结 5 401
谎友^
谎友^ 2020-12-16 23:31

I want to search through RecyclerView, I have List (BaseOfCards is my getter&setter class) My RecyclerViewAdapter<

5条回答
  •  粉色の甜心
    2020-12-17 00:15

    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();
            }
        }
    }
    

提交回复
热议问题