我的应用程序有一个自定义的ListView-Adapter,可以将listview_item扩展到一个ListView中,它有多个TextView。
我已经在布局中添加了一个SearchView,但是我希望它能够搜索ListView并通过查看SearchView中输入的数据是否与listview_items中TextViews中的任何数据相同来过滤它。
答案 0 :(得分:0)
在您的acitivity类中覆盖OnQueryTextListener,如:
@Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
mAdapter.getFilter().filter(query);
return true;
}
在内部适配器中,实现过滤器,如:
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
}