【发布时间】:2021-01-12 17:00:08
【问题描述】:
我有主片段和对话框片段。在开始时,我进入带有城市列表的 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
}
}
【问题讨论】:
-
我可以建议使用来自 ktx 扩展的
by viewModels()和by activityViewModels吗?见developer.android.com/topic/libraries/architecture/viewmodel
标签: android kotlin android-livedata android-viewmodel mutablelivedata