heiligbasil
heiligbasil

Reputation: 149

How to use the Navigation Graph without loading a fragment by default?

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?

Upvotes: 2

Views: 3145

Answers (2)

krunal bakhal
krunal bakhal

Reputation: 11

Add **app:allowStacking=false** to xml file having tag <androidx.fragment.app.FragmentContainerView> or <fragment>. This will avoid loading fragment which set at start destination.
<androidx.fragment.app.FragmentContainerView
                android:id="@+id/setting_nav_host_fragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:allowStacking="false"
                app:navGraph="@navigation/settings_graph" />

Upvotes: 0

Farid
Farid

Reputation: 1096

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

Upvotes: 1

Related Questions