I just started to use kotlin and room database, in my fragment i have a RecyclerView
and an EditText
which i would use as search for the RecyclerView
. The RecyclerView's adapter is inside my ViewModel
observable and i've actually set a TextWatcher to my EditText
but as the data of the RecyclerView comes from my room DataBase how should i set that filtering?
When the EditText is empty i should return items from the LiveData observable..
Here is my Fragment code:
private lateinit var recyclerView: RecyclerView
private lateinit var txtSearch: EditText
private val articoliViewModel: ArticoliViewModel
get() = (activity as MainActivity).articoliViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = view.findViewById(R.id.recyclerView)
txtSearch = view.findViewById(R.id.txtSearch)
val adapter = ArticoliListAdapter()
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(activity)
articoliViewModel.articoli.observe(viewLifecycleOwner) { articoli ->
// Update the cached copy of the words in the adapter.
articoli.let { adapter.submitList(it) }
}
txtSearch.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
}