ViewHolder 中的 FragmentContainerView - 哪个是合适的 FragmentManager?

FragmentContainerView in ViewHolder - which is the appropriate 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 来配置片段?

documentation 声明它 ".. add the Fragment to the appropriate FragmentManager" 你应该可以通过标签访问它。

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

那会是哪个?

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

"View androidx.fragment.app.FragmentContainerView... app:id/productRecommendationSectionFragment} does not have a Fragment set"

编辑:

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

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

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

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

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

  • RecyclerView 行中的片段,其中 RecyclerView FragmentActivity: Activity.getSupportFragmentManager()

现在前两个都有很好的记录,这里不感兴趣,但我发现第三个案例令人惊讶,特别是因为 RecyclerView 被膨胀成什么似乎没有什么区别.如果我不得不猜测这是为什么,它可能在 onCreateViewHolder 中。当你膨胀你的行时,你将 false 传递给膨胀函数的 attachToRoot,因此 FragmentContainerView 在初始化时没有附加到父级,它必须使用最高级别的片段管理器 - 来自 activity。然而这只是猜测。

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


你还说你已经尝试过使用所有的片段管理器,但它们都找不到你的片段,但我无法重现这个问题。我设法在 RecyclerView 中找到了我的片段,所以我希望还有一些我们无法从您显示的代码中找到的东西,理论上它是有效的。