'Android Navigation Component: dynamically adding fragment to graph

I got a question about using Navigation Architecture Component. I have defined a navigation graph to my app and it works perfectly but I need to use framework SDK. This framework handles some deeplinks and returns fragments in the callback. So far I used fragmentManager to add these fragments but I decided to use the navigation component in the new app. Is any way to add this fragment to the graph after getting it?



Solution 1:[1]

// Here is working sample SecondFragment not registered in //my_nav_host_fragment

 val navHostFragment = requireActivity().supportFragmentManager
            .findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController
        //navController.navigatorProvider
        val fragmentNavigator =
            navController.navigatorProvider.navigators.get("fragment") as FragmentNavigator
        
        val fragmentNavDest = FragmentNavigatorDestinationBuilder(
            fragmentNavigator,
            "SecondFragment",
            SecondFragment::class
        ).build()
        
        navController.graph.addDestination(fragmentNavDest)
        navController.navigate("SecondFragment")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kuldeep Saini