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

1

6

I have a single Activity application. I created a single Navigation graph containing all the possible destinations (Fragment).

The Activity layout only contains a <fragment/> container as it should be.

There is a main Fragment containing a BottomNavigationView where the user can navigate to all the important destinations (3 of them).

When I implement the BottomNavigationView as described in many tutorials or event in the official documentation, it replaces the full content of the Activity. Therefore, the BottomNavigationView is no more displayed as it is contained in a Fragment and not in the Activity. I want it to inflate the right layout in the main Fragment.

Should I use another Navigation graph, specific for the main Fragment ? Should I use a classic Listener (But I will loose all the interest of using a Navigation graph) ? Is there a solution I don't know ?

How do I implement it ? I tried to create two different Navigation graph, but I can not set it to my BottomNavigationView

Cinda answered 28/4, 2020 at 19:33 Comment(0)
C
9

Answer:

Create a second Navigation graph containing the destination you want your BottomNavigationView to access.

In the fragment containing the BottomNavigationView make sure to insert a FragmentContainerView and an appropriate ID.

Then, thanks to This answer right here you can implement it easily.

Juste refer to the nested NavHost using this:

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")
}
Cinda answered 30/4, 2020 at 17:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.