I need to use the navigation component and have it already set up. The navigation graph requires a startDestination
which loads that fragment by default upon creation. However, I have a fragment which I only want to show after an event is triggered within the existing screen. How could I leave the fragment container empty until I'm ready to navigate to it?
in your xml file declare your container as empty navigation host
<fragment
android:id="@+id/container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
then in your activity you can set your graph progmatically
val navHost = NavHostFragment()
fragmentManager.beginTransaction()
.replace(R.id.container, navHost)
.commit()
val graph = navHost.navController.navInflater.inflate(R.navigation.my_navigation)
graph.startDestination = R.id.my_fragment
navHost.navController.graph = graph
you can check this link