当使用Adapter的Filter来过滤数据时,可能会遇到Filter Results始终返回null的情况。这是由于Filter的performFiltering方法没有正确实现。以下是一个正确实现performFiltering方法的示例:
public class MyAdapter extends ArrayAdapter implements Filterable {
private ArrayList originalList;
private ArrayList filteredList;
private MyFilter filter;
public MyAdapter(Context context, int resource, List objects) {
super(context, resource, objects);
this.originalList = new ArrayList(objects);
this.filteredList = new ArrayList(objects);
}
@Override
public int getCount() {
return filteredList.size();
}
@Override
public String getItem(int position) {
return filteredList.get(position);
}
@Override
public Filter getFilter() {
if (filter == null) {
filter = new MyFilter();
}
return filter;
}
private class MyFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList list = new ArrayList(originalList);
if (constraint == null || constraint.length() == 0) {
results.values = list;
results.count = list.size();
} else {
String prefix = constraint.toString().toLowerCase();
final ArrayList newList = new ArrayList();
for (String item : list) {
final String itemName = item.toLowerCase();
if (itemName.contains(prefix)) {
newList.add(item);
}
}
results.values = newList;
results.count = newList.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredList = (ArrayList) results.values;
notifyDataSetChanged();
}
}
}
上述示例中的performFiltering方法会将原始数据复制到一个新的ArrayList中,并进行过滤处理。如果过滤结果不为空,则将其存储在results.values中并返回,否则返回原始数据列表。在publishResults方法中,过滤结果集合将用于更新