2.5 Filtering RecyclerViews
Creating a Filter
In order to support filtering items in our RecyclerView, we must change a few things. Take our CustomAdapter from 2.3 Implementation of a Recycler View:
class CustomAdapter(private val dataSet: List<Book>) :
RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
/**
* Provide a reference to the type of views that you are using
* (custom ViewHolder).
*/
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val bookName: TextView = view.findViewById(R.id.book_name)
val author: TextView = view.findViewById(R.id.author)
val publisher: TextView = view.findViewById(R.id.publisher)
}
// Create new views (invoked by the layout manager)
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
// Create a new view, which defines the UI of the list item
val view = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.book_row_item, viewGroup, false)
return ViewHolder(view)
}
// Replace the contents of a view (invoked by the layout manager)
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
// Get element from your dataset at this position and replace the
// contents of the view with that element
viewHolder.bookName.text = dataSet[position].bookName
viewHolder.author.text = dataSet[position].author
viewHolder.publisher.text = dataSet[position].publisher
}
// Return the size of your dataset (invoked by the layout manager)
override fun getItemCount() = dataSet.size
}
In the RecyclerView adapter, create an ArrayList with the name dataSetFiltered, and pass all the items from our original list. The rest of the adapter is now based off of this filtered list as opposed to the original data set (which should remain unchanged, acting as a source of truth for what an unfiltered list looks like):
Return the size of the dataSetFiltered as opposed to the dataSet so the right amount of items to display matches what's filtered:
Now, in the onBindViewHolder get the item for each row from the dataSetFiltered list:
Lastly, add the capabilities to filter based on some query!
Add the filter variable to your adapter:
Next, we have to implement onFilterChange:
Using the Filter
To use filter, we can simply set the value of the filter in our adapter:
We can also leverage SearchView to filter our RecyclerView by query from the user.
Last updated
Was this helpful?