【问题标题】:Trouble with ViewModel, LiveDataViewModel、LiveData 出现问题
【发布时间】: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
    }
}

【问题讨论】:

标签: android kotlin android-livedata android-viewmodel mutablelivedata


【解决方案1】:

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

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

如果你传递Fragment,你会在每个Fragment中得到不同的ViewModel。

【讨论】:

    猜你喜欢
    • 2021-01-04
    • 2019-10-10
    • 2021-01-24
    • 1970-01-01
    • 2019-07-17
    • 2020-02-18
    • 2021-07-16
    • 2018-05-10
    • 1970-01-01
    相关资源
    最近更新 更多