簡體   English   中英

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

文檔指出它".. add the Fragment to the appropriate FragmentManager" ,您應該能夠通過標簽訪問它。

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

那會是哪一個呢?

一個線索可能是在 ViewHolder 調用 binding.root.findFragment 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本身進行了一些調試之后,我希望找到了在通過android:name屬性添加片段時使用的所有FragmentManager案例。

  • 活動視圖層次結構中的片段(來自Activity.setContentView(Int) ): Activity.getSupportFragmentManager()

  • 另一個片段層次結構中的片段(來自Fragment.onCreateView(...))Fragment.getChildFragmentManager

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

現在前兩個有據可查,在這里並不感興趣,但我發現第三種情況令人驚訝,特別是因為它似乎沒有影響RecyclerView的膨脹程度。 如果我不得不猜測這是為什么,它可能會在onCreateViewHolder中。當你膨脹你的行時,你將false傳遞給 inflate 函數的attachToRoot ,因此FragmentContainerView在初始化時沒有附加到父級,它有從活動中使用最高級別的片段管理器。 然而,這只是猜測。

無論如何,在回答您的問題時 - 它絕對是活動片段管理器。


您還說您已經嘗試使用所有片段管理器並且他們都找不到您的片段,但我無法復制這個問題。 我設法在RecyclerView中找到了我的片段,所以我希望還有其他事情發生,我們無法從您顯示的代碼中找到,理論上它可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM