これが私のフィルターのコードです:
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);
}
検索ボックスに何かを入力しているときはうまく機能していたので、しばらくこれに苦労しましたが、検索フィールドからテキストを削除すると、リストが初期状態に戻りません。この問題を解決するのを手伝ってください!