Is it possible to set startDestination conditionally using Android Navigation Architecture Component(Android Jetpack)?

前端 未结 5 832
难免孤独
难免孤独 2020-12-02 11:53

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

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 12:34

    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

提交回复
热议问题