0

我的应用程序在主活动中包含一个底部导航视图,其中包含 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
        }

4

1 回答 1

0

创建NavigationExtension

使用 FragmentContainerView 加载 Fragment

 <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 应该相同

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

于 2021-05-07T05:14:30.743 回答