Reputation: 11
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)
}
Upvotes: 0
Views: 2262
Reputation: 11
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)
}
}
})
Upvotes: 0
Reputation: 1347
You can use two way data binding like below to pass data to viewmodel..
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginLeft="92dp"
android:layout_marginTop="144dp"
android:text="@={viewmodel.rememberMe}"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Upvotes: 1