I am using RecyclerView extending from ListAdapter
and implementing Filterable
interface as below.
class GroceryListAdapter(private val mContext: Context, private val viewModel: MainViewModel, groceryList: List<Grocery>) :
ListAdapter<Grocery, GroceryListAdapter.GroceryViewHolder>(GroceryDiffUtils()), Filterable {
var groceryListFull : MutableList<Grocery> = groceryList.toMutableList()
...
...
override fun getFilter(): Filter {
return ExampleFilter()
}
inner class ExampleFilter() : Filter() {
override fun performFiltering(constraint: CharSequence?): FilterResults {
val filteredList = mutableListOf<Grocery>()
if (constraint.isNullOrEmpty())
filteredList.addAll(groceryListFull)
else {
val filterPattern = constraint.toString().lowercase().trim()
for (item in groceryListFull) {
if (item.name.lowercase().contains(filterPattern))
filteredList.add(item)
}
}
val results = FilterResults()
results.values = filteredList
return results
}
override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
groceryListFull.clear()
groceryListFull.addAll(results?.values as MutableList<Grocery>)
notifyDataSetChanged()
}
}
}
and inside fragment, binding results as follows:
...
...
viewModel.getGroceryList().observe(viewLifecycleOwner) {
binding.rvGroceryList.apply {
adapter = GroceryListAdapter(requireActivity(), viewModel, it)
layoutManager = LinearLayoutManager(activity?.baseContext!!)
(binding.rvGroceryList.adapter as GroceryListAdapter).submitList(it)
}
}
binding.groceryItemSearch.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(newText: String): Boolean {
(binding.rvGroceryList.adapter as GroceryListAdapter).filter.filter(newText)
return false
}
})
When I tried searching, list is not getting filtered. I debugged the filter code adapter, it is working as expected, but not seeing visual changes in the list. What am I missing?