You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVVM架构笔记应用中,通过ViewModel的LiveData实现按钮跳转Fragment失效问题求助

MVVM架构笔记应用中,通过ViewModel的LiveData实现按钮跳转Fragment失效问题求助

大家好,我正在开发一个采用DataBinding和完整MVVM架构的笔记应用。因为按钮用了DataBinding绑定,所以我想通过ViewModel来处理按钮点击后的Fragment导航逻辑——具体是点击按钮后跳转到另一个Fragment。

我在ViewModel里定义了MutableLiveData并暴露成LiveData,然后在Fragment中观察这个LiveData,但不知道为什么点击按钮后完全没有触发页面跳转的动作。

以下是我的代码:

ViewModel.kt

private val _openScreen = MutableLiveData<String>()

val openScreen: LiveData<String> = _openScreen

fun saveButton(){
    _openScreen.value = "R.id.action_addUpdateNote_to_allNotesFragment"
}

MyFragment.kt

viewModel.openScreen.observe(viewLifecycleOwner, Observer {
    view?.findNavController()?.navigate(it.toInt())
})

有没有大佬能帮我看看哪里出问题了?

备注:内容来源于stack exchange,提问作者SAMUEL AKRAM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 09:12:41