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

documentation 声明它 ".. 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} 没有 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 行中的片段,其中 RecyclerViewRecyclerViewFragment 中的要么:{{1 }}

现在前两个有详细记录,这里不感兴趣,但我发现第三个案例令人惊讶,特别是因为它似乎对 Activity 膨胀的内容没有影响。如果我不得不猜测为什么会这样,它可能在 Activity.getSupportFragmentManager() 中。当您对行进行膨胀时,您将 RecyclerView 传递到膨胀函数的 onCreateViewHolder 中,因此 {{ 1}} 在初始化时没有附加到父级,它必须使用最高级别的片段管理器 - 来自活动。不过这只是猜测。

不管怎样,回答你的问题——肯定是活动片段管理器。


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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...