How to pass arguments to a fragment using bottom navigation view and Android Navigation component?
If I understood you correctly, you want to pass arguments to destinations that is tied to menu items. Try to use 'OnDestinationChangedListener' inside your activity onCreate method, something like this:
navController.addOnDestinationChangedListener { controller, destination, arguments ->
when(destination.id) {
R.id.homeFragment -> {
val argument = NavArgument.Builder().setDefaultValue(6).build()
destination.addArgument("Argument", argument)
}
}
}
Update:
If you want that your start destination will receive default arguments the implementation should be different. First, remove 'app:navGraph="@navigation/nav_graph"' from your 'NavHostFragment' xml tag.
Then, inside your activity onCreate you need to inflate the graph:
val navInflater = navController.navInflater
val graph = navInflater.inflate(R.navigation.nav_graph)
Then add your arguments to graph(this arguments will be attached to start destination)
val navArgument1=NavArgument.Builder().setDefaultValue(1).build()
val navArgument2=NavArgument.Builder().setDefaultValue("Hello").build()
graph.addArgument("Key1",navArgument1)
graph.addArgument("Key2",navArgument2)
Then attach the graph to NavController:
navController.graph=graph
Now your first destination should receive the attached arguments.
The correct way to do this is indeed with an <argument>
block on your destination.
<fragment android:id="@+id/homeFragment"
android:name="uk.co.homeready.homeready.HomeFragment"
android:label="fragment_home"
tools:layout="@layout/fragment_home">
<argument
android:name="Argument"
android:defaultValue="value"
/>
</fragment>
This will automatically populate the arguments of the Fragment with the default value without any additional code needed. As of Navigation 1.0.0-alpha09, this is true whether you use the Safe Args Gradle Plugin or not.