我创建了自己的适配器,扩展了BaseAdapter
类。适配器方法已实施且工作正常。
然后我将Implements Filterable
添加到此类并实现其方法:
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// has the filtered values
elements = (ArrayList<DictionaryListElement>) results.values;
// notifies the data with new filtered values. Only filtered
// values will be shown on the list
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
Locale locale = new Locale("KK");
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<DictionaryListElement>(elements); // saves // mOriginalValues
}
if (constraint == null || constraint.length() == 0) {
/* CONTRACT FOR IMPLEMENTING FILTER : set the Original values to result which will be returned for publishing */
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
ArrayList<DictionaryListElement> filteredArrayList = new ArrayList<DictionaryListElement>();
String searchword = constraint.toString();
searchword = searchword.toLowerCase(locale);
for (int i = 0; i < mOriginalValues.size(); i++) {
String word = mOriginalValues.get(i).getWord();
if (word.toLowerCase(locale).startsWith(searchword)) {
filteredArrayList.add(mOriginalValues.get(i));
}
}
// set the Filtered result to return
results.count = filteredArrayList.size();
results.values = filteredArrayList;
}
return results;
}
};
return filter;
}
然后我在我的活动中添加了SearchView
并添加到了我的活动implements OnQueryTextListener
然后我在菜单中添加了SearchView
:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
search = new SearchView(getActionBar().getThemedContext());
search.setIconified(false);
search.setSubmitButtonEnabled(false);
search.setOnQueryTextListener(this);
search.setQueryHint(getString(R.string.enter_the_word));
menu.add(0, 1, 1, null)
.setIcon(android.R.drawable.ic_search_category_default)
.setActionView(search)
.setShowAsAction(
MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return true;
}
然后我实现onQueryTextChange
方法:
@Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
if (TextUtils.isEmpty(newText)) {
dictionaryList.clearTextFilter();
} else {
dictionaryList.setFilterText(newText);
}
return true;
}
dictionaryList
是LisView
。
当我启动应用程序并在设备中键入文本时,它什么也没做!我做错了什么?
答案 0 :(得分:1)
我找到了解决方案。我需要写:
if (TextUtils.isEmpty(newText)) {
dictionaryList.clearTextFilter();
} else {
//dictionaryList.setFilterText(newText);
dictionaryList.setSelectionAfterHeaderView();
DictionaryListAdapter adapter = (DictionaryListAdapter) dictionaryList.getAdapter();
adapter.getFilter().filter(newText);
}
在onQueryTextChange