首页 > 解决方案 > ViewHolder 中的 FragmentContainerView - 哪个是合适的 FragmentManager?

问题描述

我在一行中包含一个片段RecyclerView- 我知道这不是最推荐的事情,但它使用得不多,我希望它作为一个Fragment,因为我们在多个地方使用它。

我在视图中添加了这个ViewHolder

<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 来配置片段?

文档说明它".. add the Fragment to the appropriate FragmentManager"并且您应该能够通过标签访问它。

但它似乎既不是约束 Fragment´Fragment.fragmentManagerFragment.childFragmentManager,也不是Activity.fragmentManager. (由包含片段的代表测试)

那会是哪一个呢?

一个线索可能是在 ViewHolder 调用binding.root.findFragment<ContainingFragment>()中导致IllegalStateException

“查看 androidx.fragment.app.FragmentContainerView ... app:id/productRecommendationSectionFragment} 没有片段集”

编辑:

我已经通过委托尝试了包含片段的那些片段管理器。

activity!!.supportFragmentManager.findFragmentByTag("ProductRecommendationSectionFragment") // null
childFragmentManager.findFragmentByTag("ProductRecommendationSectionFragment") // null
fragmentManager.findFragmentByTag("ProductRecommendationSectionFragment") // null

标签: androidandroid-fragmentsandroid-fragment-manager

解决方案


经过本身的一些调试FragmentContainerView,我希望在通过属性FragmentManager添加片段的同时找到所有使用的情况。android:name

  • 活动视图层次结构中的片段(来自Activity.setContentView(Int)):Activity.getSupportFragmentManager()

  • 另一个片段层次结构中的片段(来自Fragment.onCreateView(...))Fragment.getChildFragmentManager

  • RecyclerView连续的RecyclerView片段,其中aFragment或 an ActivityActivity.getSupportFragmentManager()

现在前两个有据可查,在这里并不感兴趣,但我发现第三种情况令人惊讶,特别是因为它似乎并没有什么不同RecyclerView。如果我不得不猜测这是为什么,它可能会在onCreateViewHolder。当你膨胀你的行时,你会传递false到 inflate 函数的attachToRoot,所以在FragmentContainerView初始化时它没有附加到父级,它必须使用最高的级别片段管理器 - 来自活动。然而,这只是猜测。

无论如何,在回答您的问题时 - 它绝对是活动片段管理器。


您还说您已经尝试使用所有片段管理器并且他们都找不到您的片段,但我无法复制这个问题。我设法找到了我的片段,RecyclerView所以我希望还有其他事情发生,我们无法从你展示的代码中找到,理论上它可以工作。


推荐阅读