Filterable Adapter

A filterable adapter in Android is a type of adapter that supports filtering operations, allowing the user to dynamically filter the items displayed in a RecyclerView or ListView based on certain criteria. This is particularly useful for implementing search functionalities where the displayed list of items needs to be updated in real-time as the user types a query.

To create a filterable adapter, the adapter class implements the Filterable interface, which requires the implementation of the getFilter() method. This method returns an instance of Filter that performs the actual filtering logic.

Example for Adapter

class FilterableAdapter : BaseFilterableAdapter<String, FilterableAdapter.ViewHolder>() {

    override fun getViewBinding(parent: ViewGroup, viewType: Int): ViewBinding {
        return ItemRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false)
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): FilterableAdapter.ViewHolder {
        return ViewHolder(getViewBinding(parent, viewType))
    }

    inner class ViewHolder(binding: ViewBinding) : BaseFilterableItemViewHolder<String>(binding) {
        override fun bind(data: String) = with(binding as ItemRecyclerBinding) {
            tvTitle.text = data
        }
    }
}

And then, you can call adapter.filter.filter("string filter here"). For example

filterableAdapter.filter.filter(newText)

newText is from EditText

This is the result of FilterableAdapter

Last updated