15

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?

Phantômaxx
  • 37,352
  • 21
  • 80
  • 110
amp
  • 10,768
  • 17
  • 72
  • 124
  • val navController = findNavController(R.id.nav_host) val inflater = navController.navInflater val graph = inflater.inflate(R.navigation.navigation_name) navController.graph = graph – pravingaikwad07 Aug 07 '21 at 02:22

3 Answers3

37

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

Evgenii
  • 65
  • 1
  • 8
amp
  • 10,768
  • 17
  • 72
  • 124
5

You can write in your Activity as follows.

findNavController(R.id.my_nav_host_fragment).setGraph(R.navigation.my_nav_graph)
Tatsuya Fujisaki
  • 677
  • 8
  • 12
3

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)
Thracian
  • 13,723
  • 7
  • 65
  • 116
  • `findNavController()` will search for controller in all child views and will return first controller, that is not null. If you have nested `nav_graph`s, your code can set graph to the wrong controller. – Peter Jan 19 '22 at 13:17