英文:
How to share a ViewModel between custom Views of different Fragments?
问题
你可以尝试以下方法来在这些自定义视图之间共享一个 ViewModel:
在 Activity 中创建 ViewModel,并确保在 Fragments 和自定义视图中都使用相同的 ViewModelProvider。这将确保它们共享相同的 ViewModel 实例。
在 Activity 中创建 ViewModel:
private val mainViewModel: MainViewModel by viewModels()
然后在 Fragments 和自定义视图中都使用相同的 ViewModelProvider:
// 在 Fragments 中
private val mainViewModel: MainViewModel by activityViewModels()
// 在自定义视图中
private val mainViewModel by lazy {
ViewModelProvider(findActivityViewModelStoreOwner()!!).get<MainViewModel>()
}
这样,它们将使用相同的 ViewModel 实例,实现共享 ViewModel 的效果。
英文:
I have an Activity which contains 2 Fragments which contains various custom Views each.
How can I share a ViewModel between theses custom Views?
-Fragments-
private val mainViewModel: MainViewModel by activityViewModels()
-Custom Views-
private val mainViewModel by lazy {
ViewModelProvider(findViewTreeViewModelStoreOwner()!!).get<MainViewModel>()
}
The problem is that findViewTreeViewModelStoreOwner() returns the Fragment instead of the Activity, creating a new ViewModel instead of sharing the existing one.
Is there any way to share an Activity ViewModel between the custom Views?
答案1
得分: 1
这是因为在你的自定义视图中,findViewTreeViewModelStoreOwner()
返回的是 Fragment 而不是 Activity,因为你的视图已附加到 Fragment 上,因此该方法返回 Fragment。
你可以尝试显式将你的视图的 Activity
强制转换为 ViewModelStoreOwner
,并从使用此 Activity 创建的 ViewModelProvider
获取一个 ViewModel
。然后,你的 Activity 的 ViewModel
必须被返回(Kotlin 会自动将 Activity 强制转换为 ViewModelStoreOwner,但为了清晰起见):
// 你的 Activity:
private val mainViewModel by viewModels<MainViewModel>()
// 你的自定义视图:
private val mainViewModel by lazy {
ViewModelProvider(activity as ViewModelStoreOwner).get<MainViewModel>()
}
英文:
This happens because findViewTreeViewModelStoreOwner()
in your Custom view returns Fragment instead of Activity since your View have attached to Fragment and therefore this method returns Fragment.
You can try to explicitly cast Activity
of your View
to ViewModelStoreOwner
and get a ViewModel
from ViewModelProvider
created with this Activity. Then, ViewModel
of your Activity has to be returned (Kotlin would do automatic type cast Activity to ViewModelStoreOwner, but just for clarity):
// Your Activity:
private val mainViewModel by viewModels<MainViewModel>()
// Your custom views:
private val mainViewModel by lazy {
ViewModelProvider(activity as ViewModelStoreOwner).get<MainViewModel>()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论