android - 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.fragmentManager
或Fragment.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
解决方案
经过本身的一些调试FragmentContainerView
,我希望在通过属性FragmentManager
添加片段的同时找到所有使用的情况。android:name
活动视图层次结构中的片段(来自
Activity.setContentView(Int)
):Activity.getSupportFragmentManager()
另一个片段层次结构中的片段(来自
Fragment.onCreateView(...))
:Fragment.getChildFragmentManager
RecyclerView
连续的RecyclerView
片段,其中aFragment
或 anActivity
:Activity.getSupportFragmentManager()
现在前两个有据可查,在这里并不感兴趣,但我发现第三种情况令人惊讶,特别是因为它似乎并没有什么不同RecyclerView
。如果我不得不猜测这是为什么,它可能会在onCreateViewHolder
。当你膨胀你的行时,你会传递false
到 inflate 函数的attachToRoot
,所以在FragmentContainerView
初始化时它没有附加到父级,它必须使用最高的级别片段管理器 - 来自活动。然而,这只是猜测。
无论如何,在回答您的问题时 - 它绝对是活动片段管理器。
您还说您已经尝试使用所有片段管理器并且他们都找不到您的片段,但我无法复制这个问题。我设法找到了我的片段,RecyclerView
所以我希望还有其他事情发生,我们无法从你展示的代码中找到,理论上它可以工作。
推荐阅读
- excel - Excel:从筛选器中复制所选项目
- amazon-web-services - 使用邮递员调用 S3 预签名 URL
- visual-studio-code - Mac OS - 以管理员权限运行 VS Code,以便应用更改
- android - RemoteServiceException:Context.startForegroundService 没有调用 Service.startForeground
- python - 抓取网页时如何单击下一步按钮
- iis - IIS 应用程序 HTTP 方法停止运行
- excel - 如何比较工作表中的数据并在不同的工作表中操作?
- visual-studio-2019 - 你能修复“cl.exe 失败,退出状态为 2”吗?
- java - sdkman 挂钩将 /etc/ssl/java/cacerts 链接到当前使用的 Java SDK
- c# - 使用 LINQ 创建 DataTable 以选择多个列