【问题标题】:Change fragment from ViewModel in MVVM architecture在 MVVM 架构中从 ViewModel 更改片段
【发布时间】:2021-07-27 15:41:06
【问题描述】:

我正在为练习 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()
        }
    }

【问题讨论】:

  • 你不应该在 ViewModel 中这样做,应该在 Fragment OR Activity 中这样做。
  • 使用活动?.supportFragmentManager
  • 扩展@QAMAR 评论。按照惯例,ViewModel 应该对按钮点击之类的事情做出反应,即onNewSearch(text : String) - 只有当ViewModel 有理由更改状态/数据时。相反,View 只需要观察状态和数据的变化,无论是实时数据、实时数据 + 数据绑定、状态流、状态流 + 数据绑定、可组合等 .. 您的 fragmentChanger 并不代表状态或数据更改为ViewModel 因此不属于那里。但是,由于您的方法,系统将调用 ViewModel::onCleared 作为副作用,这是状态更改。

标签: android kotlin mvvm


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-02-26
    • 1970-01-01
    • 2017-10-24
    • 2020-07-28
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多