I have main Fragment and DialogFragment. In Start i go in dialogFragment with list of city and get one for save in LiveData
listOfCities.setOnItemClickListener { parent, view, position, id ->
homeViewModel.selectCityTo((listOfCities.getItemAtPosition(position) as HashMap<String, String>).getValue("name"))
Log.e("Search", homeViewModel.cityTo.value)
}
I checked through Logcat and its work. But when i returned to main Fragment, Livedata is empty. TextView(cityTo) does not change
homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_home, container, false)
val cityFrom = root.findViewById<TextView>(R.id.cityFrom)
val cityTo = root.findViewById<TextView>(R.id.cityTo)
homeViewModel.cityFrom.observe(viewLifecycleOwner, Observer {
cityFrom.text = it
})
homeViewModel.cityTo.observe(viewLifecycleOwner, Observer {
cityTo.text = it
})
ViewModel
class HomeViewModel : ViewModel() {
private val _cityFrom = MutableLiveData<String>()
private val _cityTo = MutableLiveData<String>()
val cityFrom: LiveData<String> = _cityFrom
val cityTo: LiveData<String> = _cityTo
fun selectCityTo(to: String){
_cityTo.value = to
Log.e("hViewModel", "${cityTo.value}")
}
fun selectCityFrom(from: String){
_cityFrom.value = from
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…