2 回答
TA贡献1790条经验 获得超9个赞
适配器内部:
public class ItemAdapter extends RecyclerView.Adapter<ItemHolder> implements Filterable {
private Context iContext;
private List<Items> itemsList = new ArrayList<>();
private List<Items> itemsListFilter = new ArrayList<>();
public ItemAdapter(List<Items> itemsList, Context context) {
this.itemsList = itemsList;
this.itemsListFilter = itemsList;
iContext = context;
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
itemsList = (List<Items>) results.values;
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<Items> filteredList = new ArrayList<>();
String searchText = constraint.toString().toLowerCase();
String[] split = searchText.split(",");
ArrayList<String> searchGenres = new ArrayList<>(split.length);
for (String aSplit : split) {
// remove spaces
String trim = aSplit.trim();
// skip empty entries
if (trim.length() > 0)
searchGenres.add(trim);
}
for (Items dataNames : itemsListFilter) {
// filter by title
if (dataNames.getItem().toLowerCase().trim().contains(searchText)) {
filteredList.add(dataNames);
}
}
results.count = filteredList.size();
results.values = filteredList;
return results;
}
};
return filter;
}
}
在:ItemListActivity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.YOUR_MENU, menu);
MenuItem item = menu.findItem(R.id.searchMenu);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String newText) {
itemAdapter.getFilter().filter(newText);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
菜单
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/searchMenu"
android:icon="@drawable/ic_action_search"
android:title="@string/search_title"
app:actionViewClass="androidx.appcompat.widget.SearchView"
app:showAsAction="collapseActionView|ifRoom" />
</menu>
TA贡献1831条经验 获得超4个赞
首先添加上面的类 ItemAdapter for intialize;private ArrayList<Items> arraylist;
并将此代码添加到类 ItemAdapter 中:
public void filterAll( String Qty ) {
itemsList.clear();
if (Qty.length() < 0) {
itemsList.addAll(arraylist);
} else {
for (Items ls : arraylist) {
if (ls.getqty().contains(qty) ) {
itemsList.add(ls);
}
}
notifyDataSetChanged();
}
现在在类 ItemListActivity in part onQueryTextChange 中:
itemAdapter.filterall(s.tostring());
添加回答
举报