[英]How to share a ViewModelProvider.Factory instance between Activities
I have a ViewModelProvider.Factory instance that is responsible for instantiating ViewModels and injecting repositories into the ViewModels.我有一个 ViewModelProvider.Factory 实例,负责实例化 ViewModel 并将存储库注入 ViewModel。
This works well for Fragments as I simply supply my custom Fragment factory with the ViewModel factory:这适用于 Fragments,因为我只是为我的自定义 Fragment 工厂提供 ViewModel 工厂:
this.supportFragmentManager.fragmentFactory = MyFragmentFactory(myViewModelFactory)
The fragment factory injects the ViewModel factory into the Fragments when instantiating them.片段工厂在实例化片段时将 ViewModel 工厂注入片段中。 The Fragments can then access the ViewModels through:然后片段可以通过以下方式访问 ViewModel:
mapViewModel = ViewModelProvider(this, myViewModelFactory).get(MyViewModel::class.java)
However, I want to launch a new Activity that will also require access to the same ViewModel factory.但是,我想启动一个新的Activity ,它也需要访问同一个 ViewModel 工厂。
Can I share my ViewModelProvider.Factory instance across Activities without using a global variable?我可以在不使用全局变量的情况下跨活动共享我的 ViewModelProvider.Factory 实例吗?
Use the Common class concept.使用常见的 class 概念。 Make a common class and a public static variable of your required Datatype and store values there and when you need to access just use Common.YOUR_VARIABLE_NAME;制作所需数据类型的公共 class 和公共 static 变量并将值存储在那里,当您需要访问时只需使用 Common.YOUR_VARIABLE_NAME;
Public class Common{
public static REQUIRED_DATATYPE variableName;
}
store the value which you need to access in another activity as将您需要在另一个活动中访问的值存储为Common.variableName = YOUR_VALUE;
and when you need to use just type Common.variableName
当您需要使用时,只需键入Common.variableName
Feel free to ask if something is unclear.随意询问是否有不清楚的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.