Individual Navigation graph for each Bottom navigation view menu item - Android

1.5k Views Asked by At

My application contains a bottom navigation view with 3 menu items in the main activity, each menu item inflates respective navigation graphs in the navigation container view. Each graph has 2 or more fragments connected via actions.

The problem here is during screen orientation change the application gets crashed. Also, bottom navigation does not preserve navigation graphs's state and there is no backstack maintained for the bottom navigation.

Code sample below.

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

There are 1 best solutions below

0
On

Create NavigationExtension class

take FragmentContainerView to load fragments

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

Setup NavigationGraph in the Activity

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
    }

Note: Bottom navigation item id and navigation graph id should be the same

for more detail you can refer to this sample project