How to filter a RecyclerView with a SearchView

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

    simply create two list in adapter one orignal and one temp and implements Filterable.

        @Override
        public Filter getFilter() {
            return new Filter() {
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    final FilterResults oReturn = new FilterResults();
                    final ArrayList results = new ArrayList<>();
                    if (origList == null)
                        origList = new ArrayList<>(itemList);
                    if (constraint != null && constraint.length() > 0) {
                        if (origList != null && origList.size() > 0) {
                            for (final T cd : origList) {
                                if (cd.getAttributeToSearch().toLowerCase()
                                        .contains(constraint.toString().toLowerCase()))
                                    results.add(cd);
                            }
                        }
                        oReturn.values = results;
                        oReturn.count = results.size();//newly Aded by ZA
                    } else {
                        oReturn.values = origList;
                        oReturn.count = origList.size();//newly added by ZA
                    }
                    return oReturn;
                }
    
                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(final CharSequence constraint,
                                              FilterResults results) {
                    itemList = new ArrayList<>((ArrayList) results.values);
                    // FIXME: 8/16/2017 implement Comparable with sort below
                    ///Collections.sort(itemList);
                    notifyDataSetChanged();
                }
            };
        }
    

    where

    public GenericBaseAdapter(Context mContext, List itemList) {
            this.mContext = mContext;
            this.itemList = itemList;
            this.origList = itemList;
        }
    

提交回复
热议问题