Searchview that filters a listview, with custom li

2019-09-07 20:23发布

问题:

My app has got a custom ListView-Adapter that inflates a listview_item, which has multiple TextViews into a ListView.

I have added a SearchView to the layout but I want have it so that it can search the ListView and filter it by looking if the data typed in the SearchView is the same as any of the data in the TextViews from the listview_items.

回答1:

Override OnQueryTextListener in your acitivity class like :

@Override
public boolean onQueryTextChange(String newText) {
    mAdapter.getFilter().filter(newText);
    return true;
}

@Override
public boolean onQueryTextSubmit(String query) {
    mAdapter.getFilter().filter(query);
    return true;
}

And inside adapter, implement filter like :

public Filter getFilter() {
    if (mFliter == null)
        mFliter = new CustomFilter();
    return mFliter;

}
    private class CustomFilter extends Filter {
        // called when adpater filter method is called
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            constraint = constraint.toString().toLowerCase();
            FilterResults result = new FilterResults();
            if (constraint != null && constraint.toString().length() > 0) {
                ArrayList<CustomObject> filt = new ArrayList<CustomObject>(); //filtered list
                for (int i = 0; i < originalList.size(); i++) {
                    CustomObject m = originalList.get(i);
                    if (m.getName().toLowerCase().contains(constraint)) {
                        filt.add(m); //add only items which matches
                    }
                }
                result.count = filt.size();
                result.values = filt;
            } else { // return original list
                synchronized (this) { 
                    result.values = originalList;
                    result.count = originalList.size();
                }
            }
            return result;
        }

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {
            if (results != null) {
                setList((ArrayList<CustomObject>) results.values); // notify data set changed
            } else {
                setList((ArrayList<CarObject>) originalList);
            }
        }
    }

    public void setList(ArrayList<CarObject> data) {
        mList = data; // set the adapter list to data
        YourAdapter.this.notifyDataSetChanged(); // notify data set change
    }