Search through RecyclerView using Searchview
I solved my problem
Make my class RecyclerViewAdapter
implements Filterable
Add line
private List<BaseOfCards> orig;
Add method
getFilter
in RecyclerViewAdapterpublic Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { final FilterResults oReturn = new FilterResults(); final List<BaseOfCards> results = new ArrayList<BaseOfCards>(); if (orig == null) orig = items; if (constraint != null){ if(orig !=null & orig.size()>0 ){ for ( final BaseOfCards g :orig) { if (g.getCardName().toLowerCase().contains(constraint.toString()))results.add(g); } } oReturn.values = results; } return oReturn; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { items = (ArrayList<BaseOfCards>)results.values; notifyDataSetChanged(); } };
Make MainActivity
implements SearchView.OnQueryTextListener
and change methodonQueryTextChange
:@Override public boolean onQueryTextChange(String newText) { if ( TextUtils.isEmpty ( newText ) ) { adapter.getFilter().filter(""); } else { adapter.getFilter().filter(newText.toString()); } return true; }
I want to add to ololoking answer.
In MainActivity
we should also add next code so it would work:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setIconifiedByDefault(true);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
Thanks ololoking for your answer. It helped me.