Reputation: 12352
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?
Upvotes: 23
Views: 24628
Reputation: 1760
In Java:
FragmentManager fragmentManager = getChildFragmentManager();
NavHostFragment navHostFragment = NavHostFragment.create(R.navigation.nav_graph);
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.nav_host_fragment, navHostFragment);
transaction.setPrimaryNavigationFragment(navHostFragment);
transaction.commit();
Upvotes: 0
Reputation: 89
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
Upvotes: 1
Reputation: 66674
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)
Upvotes: 5
Reputation: 1971
You can write in your Activity as follows.
findNavController(R.id.my_nav_host_fragment).setGraph(R.navigation.my_nav_graph)
Upvotes: 7
Reputation: 12352
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
Upvotes: 47