ViewModel、LiveData 的问题
Trouble with ViewModel, LiveData
我有主片段和对话框片段。在“开始”中,我进入带有城市列表的 dialogFragment,并获取一个用于保存在 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
})
视图模型
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
}
}
您应该将 activity 传递给 ViewModelProvider(在您创建视图模型的两个片段中):
ViewModelProvider(requireActivity()).get(HomeViewModel::class.java)
如果你传递Fragment,你会在每个Fragment中获得不同的ViewModel。
我有主片段和对话框片段。在“开始”中,我进入带有城市列表的 dialogFragment,并获取一个用于保存在 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
})
视图模型
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
}
}
您应该将 activity 传递给 ViewModelProvider(在您创建视图模型的两个片段中):
ViewModelProvider(requireActivity()).get(HomeViewModel::class.java)
如果你传递Fragment,你会在每个Fragment中获得不同的ViewModel。