I have an activity A that start activity B passing to it some intent data. Activity B host a navigation graph from the new Navigation Architecture Component.I want to pass t
OK, I found a solution to that problem thanks to Ian Lake from the Google team. Let say you have an activity A that will start activity B with some intent data and you want to get that data in the startDestination you have two options here if you using safe args which is my case you could do
StartFragmentArgs.fromBundle(requireActivity().intent?.extras)
to read the args from the Intent. If you don't use safe args you can extract the data from the bundle your self-using requireActivity().intent?.extras
which will return a Bundle you can use instead of the fragment getArguments()
method. That's it I try it and everything works fine.
TLDR: You have to manually inflate the graph, add the keys/values to the defaultArgs, and set the graph on the navController
.
Step 1
The documentation tells you to set the graph in the <fragment>
tag in your Activity
's layout. Something like:
<fragment
android:id="@+id/navFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:graph="@navigation/nav_whatever"
app:defaultNavHost="true"
/>
REMOVE the line setting the graph=
.
Step 2
In the Activity that will be displaying your NavHostFragment
, inflate the graph like so:
val navHostFragment = navFragment as NavHostFragment
val inflater = navHostFragment.navController.navInflater
val graph = inflater.inflate(R.navigation.nav_whatever)
Where navFragment
is the id you gave your fragment in XML, as above.
Step 3 [Crucial!]
Create a bundle to hold the arguments you want to pass to your startDestination
fragment and add it to the graph's default arguments:
val bundle = Bundle()
// ...add keys and values
graph.addDefaultArguments(bundle)
Step 4
Set the graph on the host's navController
:
navHostFragment.navController.graph = graph
After reading the solution i made one that suits for my needs, this solution assume that the data sent to the activity that host this graph
on the start destination:
@Override
public void onAttach(Context context) {
super.onAttach(context);
// work around get get starting destination with activity bundle
userId = getActivity().getIntent().getIntExtra(KEY_USER_ID, -1);
}