How to add Search in RecyclerView using Kotlin
- January 13, 2020
- John Codeos
Today, I will show you how to search for items in a RecyclerView using SearchView.
In this example, we have a RecyclerView already set up, and the only thing we do is to add the searching functionality.
We have a list of countries as sample data and using the search field we get the country we want faster.
Adding SearchView in RecyclerView
Add the SearchView in your layout, inside a LinearLayout with a vertical orientation.
In the RecyclerView adapter (In this example, RecyclerView_Adapter.kt), create an ArrayList with a name countryFilterList, and pass all the items..
Return the size of countryFilterList so every time will return the right amount of items that match the characters you typing in the SearchView.
Now, in the onBindViewHolder get the item for each row from the countryFilterList array.
Add the Filterable class in the RecyclerView_Adapter and the method getFilter()
Inside the getFilter() method, return a Filter() object:
The performFiltering method checks if we have typed a text in the SeachView.
If there is not any text, will return all items.
If there is a text, then we check if the characters match the items from the list and return the results in a FilterResults type.
The publishResults get these results, passes it to the countryFilterList array and updates the RecyclerView.
Go back to the Activity file (MainActivity.kt) and add the setOnQueryTextListener.
The onQueryTextChange method called every time we typing on the SearchView and updates the RecyclerView with the new results.
Customizing the SearchView
If you want to change the color of the search icon (magnifying glass):
For the color of the cancel button:
And to change the text color of the TextView:
You can find the final project here
If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!