SharedViewModel from viewpager2 and my parent Fragment(来自 viewpager2 和我的父片段的 SharedViewModel)
问题描述
所以,我有一个片段,我们称之为片段 A,我需要它作为我的 sharedviewmodel 的主要宿主.
So, I have one fragment, lets call it Fragment A, in which I need it to be the main host of my sharedviewmodel.
所以我是这样的
现在,在 Fragment A 中,我设置了 viewpager2 适配器
Now, inside Fragment A, I set viewpager2 Adapter
在这里我实例化了我的 FragmentProduct,它位于视图页面的 Fragment A 中,但我的适配器需要一个 FragmentActivity
Here I instantiate my FragmentProduct which is inside Fragment A in a viewpager, but my adapter needs a FragmentActivity
所以,从 FragmentA 中包含的 FragmentProducts,我需要与这个视图模型共享数据,但是当我这样做是为了将数据从这个 FragmentA 共享到 FragmentA
So, from FragmentProducts that is contained inside FragmentA, I need to share data with this viewmodel, but when I do this to share data from this fragment to FragmentA
我收到以下错误
java.lang.IllegalStateException: Fragment FragmentProducts{6953da8}(3a2f5cbb-113d-4ed2-8f85-56e04fcea356) f0} 不是子片段,它直接附在com.example.MainActivity@dcc2679
java.lang.IllegalStateException: Fragment FragmentProducts{6953da8} (3a2f5cbb-113d-4ed2-8f85-56e04fcea356) f0} is not a child Fragment, it is directly attached to com.example.MainActivity@dcc2679
所以,这告诉我 FragmentProducts 引用了我的 MainActivity,这就是逻辑,因为适配器的实例在 FragmentActivity 需要 requireActivity()
so , this is telling me that FragmentProducts references to my MainActivity, and thats logic because the instance of the adapter takes requireActivity() for FragmentActivity at
所以,我需要传递我的 FragmentA 而不是 requireActivity() 作为该 viewpager 片段的主机,但是在我的 ViewPagerAdapter 中,我不能传递 FragmentStatePagerAdapter 或其他东西来传递我的 FragmentA 作为该 viewpager 的上下文
So, I need to pass instead of requireActivity() my FragmentA as the host of this viewpager fragment but at my ViewPagerAdapter, I cant pass FragmentStatePagerAdapter or something else to pass my FragmentA as the context for that viewpager
由于我使用 viewpager2,有没有办法让 FragmentA 托管 FragmentProducts viewpager,这样我就可以像这样在我的 FragmentProducts 中获取它
Since Im using viewpager2, is there a way to let FragmentA host FragmentProducts viewpager so I can get it in my FragmentProducts like this
谢谢
推荐答案
你正在使用 FragmentStateAdapter(fragmentActivity)
.不要那样做.将您的父 Fragment 传递给 MyViewPageAdapter
并将 that 传递给 FragmentStateAdapter
.
You're using FragmentStateAdapter(fragmentActivity)
. Don't do that. Pass your parent Fragment to MyViewPageAdapter
and pass that to FragmentStateAdapter
.
这篇关于来自 viewpager2 和我的父片段的 SharedViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!