Start a Project

Android applying search and updating the items of a Recycler View

In this blog , we will learn on how to implement the search on items of a recycler view and show only the items that are related to the key value searched for.

APPROACH :

  1. Create a class say MyFilter that extends Filter class.
  2. Make a constructor of MyFilter that takes in two parameters viz,  Adapter associated with your recycler view  and list that is currently associated with the adapter.
  3. Override the “performFiltering” method and implement the logic on which you want to implement the search.
  4. Override the “publishResults” method and in this method you will typecast the default filterResults.values to the list of objects associated with your Adapter.
  5.  Make Adapterclass of your RecyclerView implements the Filterable interface.
  6. Override the “getFilter” method and this method return the object of your Filter class (MyFilter class in our case).
  7. Now set the “setOnQueryTextListener” on your search view and in “onQueryTextSubmit
    onQueryTextChange” methods get the instance of filter by calling the getFilter Method.

And this will filter the items in your recycler view. Now let’s have a look at the code to get a better understanding.Before this a brief guide to the code snippet.

The code snippet contains only the filtering part . You need to implement the  three basic methods of RecyclerView.Adapter  yourself. The user is my Object class(or model class) and a list of user is associated with the adapter. I have implemented the search on the basis of name only.

CODE :

Code for the User.class :

and finally in your search view add this code :

 

 

Exit mobile version