使用导航组件和导航图在片段内使用 BottomNavigationView 导航(不是 activity)

Navigate with BottomNavigationView inside fragment (not activity) using navigation component and navigation graph

我只有一个 Activity 申请。我创建了一个 Navigation graph 包含所有可能的目的地 (Fragment)。

Activity layout 只包含一个 <fragment/> 容器,这是应该的。

有一个包含 BottomNavigationView 的主要片段,用户可以在其中导航到所有重要的目的地(其中 3 个)。

当我按照官方文档中的许多教程或事件中描述的那样实现BottomNavigationView时,它取代了Activity的全部内容。因此,BottomNavigationView 不再显示,因为它包含在 Fragment 而不是 Activity 中。我想让它膨胀主片段中的右侧 layout

我应该使用另一个 Navigation graph,专用于主 Fragment 吗? 我应该使用经典的 Listener(但我会失去使用 Navigation graph 的所有兴趣)吗? 有没有我不知道的解决方案?

我该如何实施?我尝试创建两个不同的 Navigation graph,但我无法将其设置为我的 BottomNavigationView

答案:

创建第二个 Navigation graph,其中包含您希望 BottomNavigationView 访问的目的地。

在包含 BottomNavigationView 的片段中确保插入 FragmentContainerView 和适当的 ID。

然后,感谢 ,您可以轻松实现它。

只需使用此引用嵌套的 NavHost:

val nestedNavHostFragment = childFragmentManager.findFragmentById(R.id.bottom_nav_host) as? NavHostFragment

val navController = nestedNavHostFragment?.navController

val bottomNavigationView = view.findViewById<BottomNavigationView>(R.id.bottom_navigation)

if (navController != null) {
    bottomNavigationView.setupWithNavController(navController)
} else {
    throw RuntimeException("Controller not found")
}