2.5 Filtering RecyclerViews
Creating a Filter
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
}
Using the Filter
Last updated
Was this helpful?