How to filter a RecyclerView with a SearchView

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

    I recommend modify the solution of @Xaver Kapeller with 2 things below to avoid a problem after you cleared the searched text (the filter didn't work anymore) due to the list back of adapter has smaller size than filter list and the IndexOutOfBoundsException happened. So the code need to modify as below

    public void addItem(int position, ExampleModel model) {
        if(position >= mModel.size()) {
            mModel.add(model);
            notifyItemInserted(mModel.size()-1);
        } else {
            mModels.add(position, model);
            notifyItemInserted(position);
        }
    }
    

    And modify also in moveItem functionality

    public void moveItem(int fromPosition, int toPosition) {
        final ExampleModel model = mModels.remove(fromPosition);
        if(toPosition >= mModels.size()) {
            mModels.add(model);
            notifyItemMoved(fromPosition, mModels.size()-1);
        } else {
            mModels.add(toPosition, model);
            notifyItemMoved(fromPosition, toPosition); 
        }
    }
    

    Hope that It could help you!

提交回复
热议问题