ViewModel、LiveData出现问题



我有主片段和对话框片段。在Start中,我进入带有城市列表的对话片段,并在LiveData 中保存一个

listOfCities.setOnItemClickListener { parent, view, position, id ->
homeViewModel.selectCityTo((listOfCities.getItemAtPosition(position) as HashMap<String, String>).getValue("name"))
Log.e("Search", homeViewModel.cityTo.value)
}

我查看了Logcat及其工作。但当我返回主片段时,Livedata是空的。TextView(cityTo(不更改

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
}
}

您应该将活动传递给ViewModelProvider(在创建视图模型的两个片段中(:

ViewModelProvider(requireActivity()).get(HomeViewModel::class.java)

如果您传递片段,您将在每个片段中获得不同的ViewModel。

最新更新