In my activity layout, I have the following NavHostFragment
:
<fragment
android:id="@+id/my_nav_host_fragment"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:name="androidx.navigation.fragment.NavHostFragment"
app:defaultNavHost="true"
app:navGraph="@navigation/my_nav_graph" />
My question is how can I set the navGraph programmatically? How can I convert the my_nav_host_fragment
view instance in a NavHostFragment
instance?
I found a solution:
//Setup the navGraph for this activity
val myNavHostFragment: NavHostFragment = my_nav_host_fragment as NavHostFragment
val inflater = myNavHostFragment.navController.navInflater
val graph = inflater.inflate(R.navigation.my_nav_graph)
myNavHostFragment.navController.graph = graph
Based on: Navigation Architecture Component- Passing argument data to the startDestination
You can write in your Activity as follows.
findNavController(R.id.my_nav_host_fragment).setGraph(R.navigation.my_nav_graph)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With