amp
amp

Reputation: 12352

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?

Upvotes: 23

Views: 24628

Answers (5)

Alberto M
Alberto M

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

RIYAS PULLUR
RIYAS PULLUR

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

Thracian
Thracian

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

Tatsuya Fujisaki
Tatsuya Fujisaki

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

amp
amp

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

Related Questions