19

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,901
  • 21
  • 84
  • 115
amp
  • 11,754
  • 18
  • 77
  • 133

4 Answers4

43

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
  • 105
  • 1
  • 9
amp
  • 11,754
  • 18
  • 77
  • 133
7

You can write in your Activity as follows.

findNavController(R.id.my_nav_host_fragment).setGraph(R.navigation.my_nav_graph)
Tatsuya Fujisaki
  • 1,434
  • 15
  • 18
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)
Thracian
  • 43,021
  • 16
  • 133
  • 222
  • `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
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
RIYAS PULLUR
  • 13
  • 1
  • 4