[英]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.