20

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?

0

4 Answers 4

44

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

5
7

You can write in your Activity as follows.

findNavController(R.id.my_nav_host_fragment).setGraph(R.navigation.my_nav_graph)
5

Both of the answers caused exception when i used with DynamicNavHostFragment, so i used

val navHostFragment: NavHostFragment = supportFragmentManager
    .findFragmentById(R.id. my_nav_host_fragment) as NavHostFragment

navHostFragment.findNavController().setGraph(R.navigation. my_nav_graph)
1
  • findNavController() will search for controller in all child views and will return first controller, that is not null. If you have nested nav_graphs, your code can set graph to the wrong controller.
    – Peter
    Jan 19, 2022 at 13:17
0

My solution is this,

val myNavHostFragment = supportFragmentManager
        .findFragmentById(R.id.navHostFragmentMain) as NavHostFragment
    val inflater = myNavHostFragment.navController.navInflater
    val graph = inflater.inflate(R.navigation.nav_graph)
    myNavHostFragment.navController.graph = graph

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.