How to filter a RecyclerView with a SearchView

后端 未结 11 1847
孤独总比滥情好
孤独总比滥情好 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:46

    All you need to do is to add filter method in RecyclerView.Adapter:

    public void filter(String text) {
        items.clear();
        if(text.isEmpty()){
            items.addAll(itemsCopy);
        } else{
            text = text.toLowerCase();
            for(PhoneBookItem item: itemsCopy){
                if(item.name.toLowerCase().contains(text) || item.phone.toLowerCase().contains(text)){
                    items.add(item);
                }
            }
        }
        notifyDataSetChanged();
    }
    

    itemsCopy is initialized in adapter's constructor like itemsCopy.addAll(items).

    If you do so, just call filter from OnQueryTextListener:

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            adapter.filter(query);
            return true;
        }
    
        @Override
        public boolean onQueryTextChange(String newText) {
            adapter.filter(newText);
            return true;
        }
    });
    

    It's an example from filtering my phonebook by name and phone number.

提交回复
热议问题