繁体   English   中英

从 MVVM 架构中的 ViewModel 更改片段

[英]Change fragment from ViewModel in MVVM architecture

我正在开发一个用于实践 MVVM 架构和 SQLite 数据库的议程应用程序,但我需要从片段内部更改片段。 所以对于 calendarFragment 我创建了这个 viewModel 但我不能在没有 MainActivity 上下文的情况下使用 .supportFragmentManager 方法。 我怎么解决这个问题 ?


class calendarFragmentViewModel(application: Application) : AndroidViewModel(application) {

    fun fragmentChanger(fragment : Fragment, context: Context?) {
        var transaction = (context as MainActivity).supportFragmentManager.beginTransaction()
            transaction.replace(com.cagataysencan.agendea.R.id.frameLayout,fragment)
            transaction.commit()
        }
    }

为此,您可以将 LiveData 与 ViewModel 一起使用。

从您的 Fragment 观察 LiveData,一旦 LiveData 提供更新,我们将在 Fragment 中获取它。 在回调中,您可以从观察片段启动。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM