Android Navigation Component navigate between graphs

老子叫甜甜 提交于 2019-12-23 04:40:58

问题


I've got two navigation graphs nav_graph_red and nav_graph_blue and two Activities ActivityRed and ActivityBlue.

In each navigation graph I have a flow with 3 Fragments. redFragmentOne,redFragmentTwo,redFragmentThree and blueFragmentOne,blueFragmentTwo,blueFragmentThree

Now I want to navigate from ActivityRed - redFragmentOne to the destination blueFragmentTwo.

Is there a way to accomplish this?

I tried it this way:

Navigation.findNavController(ActivityBlue.newInstance(),R.id.host_navigation).navigate(R.id.blueFragmentTwo)

Any suggestions?


回答1:


Solution:

Start Activity with intent and pass your destination as Intent extra.

 val blueIntent = Intent(requireActivity(), ActivityBlue::class.java)
 blueIntent.putExtra("navigationStartDestination", R.id.blueFragmentTwo)
 startActivity(blueIntent)

In ActivityBlue onCreate -> get the intent extra and define navigation graph

    val startDestination = intent.getIntExtra("navigationStartDestination", 0)

    val navHostFragment = nav_host_fragment_blue as NavHostFragment
    val inflater = navHostFragment.navController.navInflater
    val graph = inflater.inflate(R.navigation.nav_graph_blue)

    graph.startDestination = startDestination
    navHostFragment.navController.graph = graph

Important!:

Remove navGraph="nav_graph_blue" in your layout xml of the ActivityBlue

<fragment
    android:id="@+id/nav_host_fragment_blue"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:layout_constraintTop_toTopOf="parent" />


来源:https://stackoverflow.com/questions/57924345/android-navigation-component-navigate-between-graphs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!