Search code examples
androidnavigationandroid-jetpack

Setting NavGraph programmatically


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?


Solution

  • 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