How to filter a RecyclerView with a SearchView

后端 未结 11 1716
孤独总比滥情好
孤独总比滥情好 2020-11-22 00:28

I am trying to implement the SearchView from the support library. I want the user to be to use the SearchView to filter a List of movi

11条回答
  •  不知归路
    2020-11-22 00:31

    Following @Shruthi Kamoji in a cleaner way, we can just use a filterable, its meant for that:

    public abstract class GenericRecycleAdapter extends RecyclerView.Adapter implements Filterable
    {
        protected List list;
        protected List originalList;
        protected Context context;
    
        public GenericRecycleAdapter(Context context,
        List list)
        {
            this.originalList = list;
            this.list = list;
            this.context = context;
        }
    
        ...
    
        @Override
        public Filter getFilter() {
            return new Filter() {
                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    list = (List) results.values;
                    notifyDataSetChanged();
                }
    
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    List filteredResults = null;
                    if (constraint.length() == 0) {
                        filteredResults = originalList;
                    } else {
                        filteredResults = getFilteredResults(constraint.toString().toLowerCase());
                    }
    
                    FilterResults results = new FilterResults();
                    results.values = filteredResults;
    
                    return results;
                }
            };
        }
    
        protected List getFilteredResults(String constraint) {
            List results = new ArrayList<>();
    
            for (E item : originalList) {
                if (item.getName().toLowerCase().contains(constraint)) {
                    results.add(item);
                }
            }
            return results;
        }
    } 
    

    The E here is a Generic Type, you can extend it using your class:

    public class customerAdapter extends GenericRecycleAdapter
    

    Or just change the E to the type you want ( for example)

    Then from searchView (the widget you can put on menu.xml):

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String text) {
            return false;
        }
    
        @Override
        public boolean onQueryTextChange(String text) {
            yourAdapter.getFilter().filter(text);
            return true;
        }
    });
    

提交回复
热议问题