导航组件:片段内的 NavHostFragment

NavigationComponent: NavHostFragment inside a fragment

我有一个带导航组件的 UI 选项卡和一个处理选项卡的 BottomNavigationView。 我的用例涉及这些选项卡片段之一,以拥有自己的 BottomNavigationView

我认为 nested navigation graphs 对我不起作用,因为我需要有一个内部 NavHostFragment 和第二个 BottomNavigationView

所以我在我希望托管我的内部导航图的片段中。它包含这样一个片段。

<androidx.fragment.app.FragmentContainerView
        android:id="@+id/inner_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost="true"

我需要一种方法来获取上述片段的导航控制器。

通常当您在 activity 中时,您会使用您为片段提供的 ID 从 supportFragmentManager 调用 findFragmentById

val navHostFragment = supportFragmentManager.findFragmentById(R.id.outer_nav_host) as NavHostFragment

所以我尝试在我的内部片段

中的 activity 对象上调用它
requireActivity().supportFragmentManager.findFragmentById(R.id.inner_host_fragment)

但是 findFragmentById returns 无效。

尝试从 supportFragmentManager 获取 NavHostFragment,然后获取 navController

val navHostFragment =
        requireActivity().supportFragmentManager.primaryNavigationFragment as NavHostFragment
val navController = navHostFragment.navController

感谢@ianhanniballake,您需要使用 childFragmentManager,因为您当前的片段是片段的子片段。

所以尝试改用:

val navHostFragment =
    childFragmentManager.primaryNavigationFragment as NavHostFragment
val navController = navHostFragment.navController

更新:

throws this java.lang.NullPointerException: null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment

所以,来自评论的解决方案:

val navHostFragment = childFragmentManager.findFragmentById(R.id.nav_host_fragment) 
                       as NavHostFragment 

并用内部 NavHostFragment 的 id 替换 nav_host_fragment