Navigation Component: Passing bundles to destinations via Bottom Navigation

1.2k Views Asked by At

In my application I have a host fragment for a group of views that a user can navigate to via a BottomNavigationView. This BottomNavigationView is connected to my nav controller via setupWithNavController.

My host fragment receives a bundle with some information that I would like each fragment to receive as it is navigated to (via the bottom nav view) as a bundle.

My current solution looks like

        mutableListOf<NavDestination>().apply {
            addIfNotNull(graph.findNode(R.id.frag1))
            addIfNotNull(graph.findNode(R.id.frag2))
            addIfNotNull(graph.findNode(R.id.frag3))

            forEach {
                // args is a safe args object for this host fragment
                it.addArgument("argName", NavArgument.Builder().setDefaultValue(args.argName).build())
            }
        }

While this works it will not scale very well as I am manually adding the arguments for each destination. Since I am not manually navigating to each destination, rather it is done by the BottomNavigationView I'm not sure how to manually add this bundle.

1

There are 1 best solutions below

1
Shrikant On
navController.addOnDestinationChangedListener { controller, dest, args ->
            when (dest.label) {
                "YOUR_LABEL_HERE" -> {
                    val arg01 = NavArgument.Builder().setDefaultValue("SOME VALUE").build()
                    val arg02 = NavArgument.Builder().setDefaultValue("SOME OTHER VALUE").build()
                    dest.addArgument("KEY_NAME", arg01)
                    dest.addArgument("OTHER_KEY_NAME", arg02)
                }
            }
        }

try this. It should work fine.