每个底部导航视图菜单项的单独导航图 - Android

时间:2021-05-06 11:04:34

标签: android android-architecture-navigation android-jetpack-navigation android-navigation-graph android-bottomnavigationview

我的应用程序包含一个底部导航视图,主活动中有 3 个菜单项,每个菜单项在导航容器视图中扩充各自的导航图。每个图都有 2 个或更多片段通过动作连接。

这里的问题是在屏幕方向更改期间应用程序崩溃。此外,底部导航不保留导航图的状态,也没有为底部导航维护后台堆栈。

下面的代码示例。

val bottomNavigation = binding.bottom_navigation_view
navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.navController

bottomNavigation.setOnNavigationItemSelectedListener{ item ->
            when(item.itemId){
                R.id.navigation_home ->{
                    val navGraph = navController.navInflater.inflate(R.navigation.nav_graph)
                    navController.graph = navGraph
                    true
                }
                R.id.navigation_search ->{
                    val searchGraph=navController.navInflater.inflate(R.navigation.search_nav_graph)
                    navController.graph = searchGraph
                    true
                }
                R.id.navigation_about ->{
                    val infoGraph = navController.navInflater.inflate(R.navigation.info_nav_graph)
                    navController.graph = infoGraph
                    true
                }
            }
            false
        }

1 个答案:

答案 0 :(得分:0)

创建 NavigationExtension

以 FragmentContainerView 加载片段

 <androidx.fragment.app.FragmentContainerView
            android:id="@+id/fragmentContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true" />

在Activity中设置NavigationGraph

private fun setupBottomNavigationBar() {
        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav)

        val navGraphIds = listOf(R.navigation.nav_graph, R.navigation.search_nav_graph, R.navigation.info_nav_graph)

        // Setup the bottom navigation view with a list of navigation graphs
        val controller = bottomNavigation.setupWithNavController(
            navGraphIds = navGraphIds,
            fragmentManager = supportFragmentManager,
            containerId = R.id.nav_host_container,
            intent = intent
        )

        // Whenever the selected controller changes, setup the action bar.
        controller.observe(this, Observer { navController ->
            setupActionBarWithNavController(navController)
        })
        currentNavController = controller
    }
<块引用>

注意:底部导航项id和导航图id要一致

有关更多详细信息,您可以参考此示例 project