简体   繁体   English

从 MVVM 架构中的 ViewModel 更改片段

[英]Change fragment from ViewModel in MVVM architecture

I am developing an agenda app for practise MVVM architecture and SQLite databases but i need to change fragment from inside of fragment.我正在开发一个用于实践 MVVM 架构和 SQLite 数据库的议程应用程序,但我需要从片段内部更改片段。 So for calendarFragment i created this viewModel but i can't use .supportFragmentManager method without MainActivity context.所以对于 calendarFragment 我创建了这个 viewModel 但我不能在没有 MainActivity 上下文的情况下使用 .supportFragmentManager 方法。 How can i solve this problem ?我怎么解决这个问题 ?


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()
        }
    }

You can use LiveData with your ViewModel for this purpose.为此,您可以将 LiveData 与 ViewModel 一起使用。

Observe the LiveData from your Fragment and once that LiveData provides an update, we'll get it in Fragment.从您的 Fragment 观察 LiveData,一旦 LiveData 提供更新,我们将在 Fragment 中获取它。 Inside the callback, you can launch from the observing fragment.在回调中,您可以从观察片段启动。

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

相关问题 在MVVM架构中从ViewModel添加片段 - Add fragment from ViewModel in MVVM architecture 在 Android MVVM 架构中显示来自 ViewModel 的对话框 - Show Dialog from ViewModel in Android MVVM Architecture MVVM体系结构中的ViewModel操作 - ViewModel manipulation in MVVM Architecture 使用架构组件 MVVM 进行身份验证,将令牌从 Repository 传递到 ViewModel - Authentication with Architecture Components MVVM, passing token from Repository to ViewModel 如何在Android的MVVM架构中将动作从View发送到ViewModel - How to send actions from View to ViewModel in MVVM architecture in Android 在 MVVM 架构中从 ViewModel 启动 Activity 的最佳方法 - Best approach to start an Activity from ViewModel in MVVM Architecture 处理ViewModel中的数据和MVVM中的Fragment - Handle data in ViewModel and Fragment in MVVM 从 MvvM 架构和 Kotlin 中的广播接收器更新片段 ui - Update fragment ui from broadcast receiver in MvvM architecture and Kotlin 单击基于 MVVM 的架构不起作用的片段的 XML 按钮的侦听器 - Click Listener of button from the XML of a fragment that is MVVM based architecture not working 使用 MVVM 架构的 ViewModel 注入(内部视图) - ViewModel injection (inside View) with MVVM Architecture
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM