如何解决ViewHolder 中的 FragmentContainerView - 哪个是合适的 FragmentManager?
我在 RecyclerView
中连续包含一个片段 - 我知道这不是最推荐的做法,但它使用不多,我希望将其作为 Fragment
我们在多个地方使用它。
<androidx.fragment.app.FragmentContainerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/productRecommendationSectionFragment"
android:name="dk.xxx.ui.sections.productRecommendation.ProductRecommendationSectionFragment"
android:layout_width="match_parent"
android:tag="ProductRecommendationSectionFragment"
android:layout_height="wrap_content" />
它按预期加载正常,但问题是如何访问正确的 FragmentManager 来配置片段?
documentation 声明它 ".. add the Fragment to the appropriate FragmentManager"
并且您应该能够通过标签访问它。
但它似乎既不是约束 Fragment´ Fragment.fragmentManager
或 Fragment.childFragmentManager
,也不是 Activity.fragmentManager
。 (由包含片段的委托测试)
那可能是什么?
一个线索可能是在 ViewHolder 中调用 binding.root.findFragment<ContainingFragment>()
导致 IllegalStateException
:
"查看androidx.fragment.app.FragmentContainerView... app:id/productRecommendationSectionFragment} 没有 Fragment 设置”
编辑:
我已经通过委托从包含片段中尝试了这些片段管理器。
activity!!.supportFragmentManager.findFragmentByTag("ProductRecommendationSectionFragment") // null
childFragmentManager.findFragmentByTag("ProductRecommendationSectionFragment") // null
fragmentManager.findFragmentByTag("ProductRecommendationSectionFragment") // null
解决方法
在对 kmovb k1,eax
本身进行一些调试之后,我希望找到通过 FragmentContainerView
属性添加片段时使用的 FragmentManager
的所有情况。
-
活动视图层次结构中的片段(来自
android:name
):Activity.setContentView(Int)
-
另一个片段层次结构中的片段(来自
Activity.getSupportFragmentManager()
:Fragment.onCreateView(...))
-
Fragment.getChildFragmentManager
行中的片段,其中RecyclerView
是RecyclerView
或Fragment
中的要么:{{1 }}
现在前两个有详细记录,这里不感兴趣,但我发现第三个案例令人惊讶,特别是因为它似乎对 Activity
膨胀的内容没有影响。如果我不得不猜测为什么会这样,它可能在 Activity.getSupportFragmentManager()
中。当您对行进行膨胀时,您将 RecyclerView
传递到膨胀函数的 onCreateViewHolder
中,因此 {{ 1}} 在初始化时没有附加到父级,它必须使用最高级别的片段管理器 - 来自活动。不过这只是猜测。
不管怎样,回答你的问题——肯定是活动片段管理器。
你还说你已经尝试使用所有的片段管理器,但他们都找不到你的片段,但我无法复制这个问题。我设法在 false
中找到了我的片段,所以我希望还有其他一些我们无法从您展示的代码中找到的东西,理论上它是有效的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。