Searchview that filters a listview, with custom listview_items

别说谁变了你拦得住时间么 提交于 2019-12-13 07:00:52

问题


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
    }


来源:https://stackoverflow.com/questions/32191000/searchview-that-filters-a-listview-with-custom-listview-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!