android tutorial - Filter items inside recyclerview with a searchview in android | Developer android - android app development - android studio - android app developement



Filter items inside recyclerview with a searchview in android

add filter method in RecyclerView.Adapter:

public void filter(String text) {
        if(text.isEmpty()){
            items.clear();
            items.addAll(itemsCopy);
        } else{
            ArrayList<PhoneBookItem> result = new ArrayList<>();
            text = text.toLowerCase();
            for(PhoneBookItem item: itemsCopy){
                //match by name or phone
                if(item.name.toLowerCase().contains(text) || item.phone.toLowerCase().contains(text)){
                    result.add(item);
                }
            }
            items.clear();
            items.addAll(result);
        }
        notifyDataSetChanged();
    }
click below button to copy code from our android learning website - android tutorial - team

itemsCopy is initialized in adapter's constructor like itemsCopy.addAll(items). If you do so, just call filter from OnQueryTextListener from SearchView:

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;
    }
});
click below button to copy code from our android learning website - android tutorial - team

Related Searches to Filter items inside recyclerview with a searchview in android