我正在尝试搜索recyclerview项目。为此,我实施了Filterable
。问题是 - 匹配项目的安装,我得到了整个项目列表。这是Adapter类的构造函数:
public RecyclerAdapter (ArrayList<List<ResponseModel>> items) {
this.items = items; // original items
this.tempItems = items; // for searching purpose
}
以下是覆盖的方法:
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String charString = constraint.toString();
if (charString.isEmpty()) {
items = tempItems;
} else {
ArrayList<List<ResponseModel>> filteredList = new ArrayList<>();
for (List<ResponseModel> responseModel : tempItems) {
for (int i =0; i < tempItems.size() ; i++) {
if (responseModel.get(i).getName().toLowerCase().contains(charString)){
filteredList.add(responseModel);
}
}
}
items = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = items;
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
items = (ArrayList<List<ResponseModel>>) results.values;
notifyDataSetChanged();
}
};
}
这是在Fragment类中的onCreate optionsMenu:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.options_menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView sv = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
MenuItemCompat.setActionView(item, sv);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return true;
}
});
}
答案 0 :(得分:0)
在publishResultsMethod
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
items.clear();
items.addAll((ArrayList<List<ResponseModel>>) results.values);
notifyDataSetChanged();
}