I need to pass an id of clicked object from AutoCompleteTextView to ViewModel. Here I have a binding adapter to set a spinner with objects for AutoCompleteTextView.
@BindingAdapter("bindAutocomplete")
fun bindAutocomplete(textView: AutoCompleteTextView, cities: List<City>?){
cities?.let {
val adapter = ArrayAdapter<City>(
textView.context,
R.layout.support_simple_spinner_dropdown_item,
it)
textView.setAdapter(adapter)
}
}
My question is: where should I place my OnItemClickListener, in this adapter above or in the Fragment class like in code below?
The problem for first way is that I dont know how to access my ViewModel from Binding Adapter. And for the second, if I put this listener in the Fragment class isn`t it breaks a pattern, because initializations of the Biniding Adapter and of the OnItemClickListener are not synchronized?
So I need to pass a city.id to some method in my ViewModel.
binding.autoCompleteTextView.setOnItemClickListener { parent, view, position, id ->
val city = parent.adapter.getItem(position) as City
binding.viewModel.getWeatherProperties(city.id)
}
So, I solved this task just by using an Observer, I am not sure if it is even possible to use a Two-way binding with AutoCompleteTextView here. Probably its because of SetOnItemClickListener has no built-in support for two-way data binding.
viewModel.autocompleteArray.observe(viewLifecycleOwner, Observer {
it?.let {
val adapter = ArrayAdapter<City>(
binding.autoCompleteTextView.context,
R.layout.support_simple_spinner_dropdown_item,
it)
binding.autoCompleteTextView.setAdapter(adapter)
binding.autoCompleteTextView.setOnItemClickListener { parent, view,
position, id ->
val s = parent.adapter.getItem(position) as City
viewModel.getWeatherProperties(s.id)
}
}
})