Android SearchView Filter ListView

前端 未结 4 1290
自闭症患者
自闭症患者 2020-11-27 16:37

I have implemented Search Filter to my SearchView in my SherlockAction Bar.

When i type m i want to show filtered results in the list view below which only starts w

4条回答
  •  有刺的猬
    2020-11-27 17:09

    Place this inside your adapter:

    @Override
    public Filter getFilter(){
       return new Filter(){
    
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                 constraint = constraint.toString().toLowerCase();
                 FilterResults result = new FilterResults();
    
                    if (constraint != null && constraint.toString().length() > 0) {
                      List founded = new ArrayList();
                            for(YourListItemType item: origData){
                                if(item.toString().toLowerCase().contains(constraint)){
                                    founded.add(item);
                                }
                        }
    
                            result.values = founded;
                            result.count = founded.size();
                        }else {
                            result.values = origData;
                            result.count = origData.size();
                        }
                return result;
    
    
        }
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
               clear();
               for (String item : (List) results.values) {
                     add(item);
               }
        notifyDataSetChanged();
    
        }
    
        }
        }
    

    And this inside constructor of your adapter

    public MyAdapter(Context context, int layoutResourceId, String[] places) {
            super(context, layoutResourceId, data);
            this.context = context;
    
            this.data = Arrays.asList(places);
            this.origData = new ArrayList(this.data);
    
     }
    

提交回复
热议问题