How to filter ListView using getFilter() in BaseAdapter

前端 未结 3 1465
长发绾君心
长发绾君心 2020-11-30 09:14

In my application I have create a custom list view and I want to implement a filter so that the list can be filtered according to the text entered in the EditText. I am usin

3条回答
  •  清歌不尽
    2020-11-30 10:10

    i hope this example could help you

    in the Main_Activity

        EditText etSearch;
        BaseAdapterFilterable adapter;
    
        etSearch.addTextChangedListener(new TextWatcher() {
    
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    // Listview name of the class
                    Listview.this.adapter.getFilter().filter(s);
                }
    
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub
    
                }
    
                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
    
                }
            });
    

    in your adapter put this class to use it in getfilter method

    public class filter_here extends Filter{
    
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                // TODO Auto-generated method stub
    
                FilterResults Result = new FilterResults();
                // if constraint is empty return the original names
                if(constraint.length() == 0 ){
                    Result.values = Original_Names;
                    Result.count = Original_Names.size();
                    return Result;
                }
    
                ArrayList Filtered_Names = new ArrayList();
                String filterString = constraint.toString().toLowerCase();
                String filterableString;
    
                for(int i = 0; i) results.values;
                notifyDataSetChanged();
            }
    
        }
    

    also in your adapter return instance from filter_here class

    @Override
        public Filter getFilter() {
            // TODO Auto-generated method stub
            return filter;
        }
    

提交回复
热议问题