How to filter a RecyclerView with a SearchView

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

    This is my take on expanding @klimat answer to not losing filtering animation.

    public void filter(String query){
        int completeListIndex = 0;
        int filteredListIndex = 0;
        while (completeListIndex < completeList.size()){
            Movie item = completeList.get(completeListIndex);
            if(item.getName().toLowerCase().contains(query)){
                if(filteredListIndex < filteredList.size()) {
                    Movie filter = filteredList.get(filteredListIndex);
                    if (!item.getName().equals(filter.getName())) {
                        filteredList.add(filteredListIndex, item);
                        notifyItemInserted(filteredListIndex);
                    }
                }else{
                    filteredList.add(filteredListIndex, item);
                    notifyItemInserted(filteredListIndex);
                }
                filteredListIndex++;
            }
            else if(filteredListIndex < filteredList.size()){
                Movie filter = filteredList.get(filteredListIndex);
                if (item.getName().equals(filter.getName())) {
                    filteredList.remove(filteredListIndex);
                    notifyItemRemoved(filteredListIndex);
                }
            }
            completeListIndex++;
        }
    }
    

    Basically what it does is looking through a complete list and adding/removing items to a filtered list one by one.

提交回复
热议问题