这是我的过滤器的代码:
private class NameFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
// NOTE: this function is *always* called from a background thread,
// and
// not the UI thread.
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if (constraint != null && constraint.toString().length() > 0) {
ArrayList<Place> filt = new ArrayList<Place>();
ArrayList<Place> lItems = new ArrayList<Place>();
synchronized (this) {
lItems.addAll(objects);
}
for (int i = 0, l = lItems.size(); i < l; i++) {
Place m = lItems.get(i);
if (m.getName().toLowerCase().contains(constraint))
filt.add(m);
}
result.count = filt.size();
result.values = filt;
}
else {
synchronized (this) {
result.values = objects;
result.count = objects.size();
}
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// NOTE: this function is *always* called from the UI thread.
filtered = (ArrayList<Place>) results.values;
notifyDataSetChanged();
clear();
for (int i = 0, l = filtered.size(); i < l; i++)
add(filtered.get(i));
notifyDataSetInvalidated();
}
}
这是我的活动代码:
lvPlace = (ListView) findViewById(R.id.listView1);
final ArrayList<Place> searchResults = GetSearchResults();
filterEditText = (EditText) findViewById(R.id.filter_text);
filterEditText.addTextChangedListener(filterTextWatcher);
adapter = new PlaceAdapter(this, 0, searchResults);
lvPlace.setAdapter(adapter);
lvPlace.requestFocus();
lvPlace.setTextFilterEnabled(true);
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (adapter != null) {
adapter.getFilter().filter(s.toString().toLowerCase());
filterEditText.getText().toString();
} else {
Log.d("filter", "no filter availible");
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
filterEditText.removeTextChangedListener(filterTextWatcher);
}
我已经为此苦苦挣扎了一段时间,因为当我在搜索框中输入内容时它工作正常,但是一旦我从搜索字段中删除了文本,列表就不会返回到初始状态。请帮我解决这个问题!