I am using Navigation from Android Jetpack to navigate between screens. Now I want to set startDestination dynamically.
I have an Activity named MainActivity And t
Finally, I got a solution to my query...
Put below code in onCreate()
method of Activity
.
Kotlin code
val navHostFragment = home_nav_fragment as NavHostFragment
val inflater = navHostFragment.navController.navInflater
val graph = inflater.inflate(R.navigation.nav_main)
graph.setDefaultArguments(intent.extras)
graph.startDestination = R.id.fragment1
//or
//graph.startDestination = R.id.fragment2
navHostFragment.navController.graph = graph
Java code
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.home_nav_fragment); // Hostfragment
NavInflater inflater = navHostFragment.getNavController().getNavInflater();
NavGraph graph = inflater.inflate(R.navigation.nav_main);
graph.setDefaultArguments(getIntent().getExtras());
graph.setStartDestination(R.id.fragment1);
navHostFragment.getNavController().setGraph(graph);
navHostFragment.getNavController().getGraph().setDefaultArguments(getIntent().getExtras());
NavigationView navigationView = findViewById(R.id.navigationView);
NavigationUI.setupWithNavController(navigationView, navHostFragment.getNavController());
Additional Info
As @artnest suggested, remove the app:navGraph
attribute from the layout. It would look something like this after removal
In the case of a fragment
tag used instead of FragmentContainerView
, the above changes remain the same