How to implement getFilter on a BaseAdapter?

前端 未结 7 832
半阙折子戏
半阙折子戏 2020-12-06 03:55

I am trying to implement a getFilter() on a base adapter to filter out search results on a List. Is there any example of how to implement a getFilter()?

MainActivity

7条回答
  •  情深已故
    2020-12-06 04:23

    getFilter() can be override in adapters and return the filter object which contains filtered list . There are two key methods in Filter() class; performFiltering and publishResults. The first method performs the filtering in worker thread and the later one return filtered list of objects.

    You can refer to sample code below

    @Override
    public Filter getFilter() {
    
            return new Filter() {
    
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    // TODO Auto-generated method stub
                    if (results.count == 0) {
                        notifyDataSetInvalidated();
                    }else{
                        mListAppInfo = (ArrayList) results.values;
                        notifyDataSetChanged();
                    }
                }
    
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    // TODO Auto-generated method stub
                    FilterResults results = new FilterResults();
    
                    if (constraint == null || constraint.length() == 0) {
                        results.values = mListAppInfo;
                        results.count = mListAppInfo.size();
                    }else{
                        ArrayList filter_items = new ArrayList<>(); 
                        for (SampleItem item : mListAppInfo) {
                            if (item.getItemName().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                                filter_items.add(item);
                            }
                        }
                        results.values =  filter_items ;
                        results.count = filter_items.size();
                    }
                    return results;
                }
            };
        }
    

    Hope you find it useful .

提交回复
热议问题