如何在不同Fragment的自定义视图之间共享ViewModel?

huangapple go评论60阅读模式
英文:

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&lt;MainViewModel&gt;()
}

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&lt;MainViewModel&gt;()

// Your custom views:
private val mainViewModel by lazy {
    ViewModelProvider(activity as ViewModelStoreOwner).get&lt;MainViewModel&gt;()
}

huangapple
  • 本文由 发表于 2023年5月6日 17:49:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188227.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定