我有两个导航图nav_graph_red
和nav_graph_blue
以及两个活动ActivityRed
和ActivityBlue
。
在每个导航图中,我都有3个片段的流程。 redFragmentOne
,redFragmentTwo
,redFragmentThree
和blueFragmentOne
,blueFragmentTwo
,blueFragmentThree
现在,我想从ActivityRed
-redFragmentOne
导航到目的地blueFragmentTwo
。
有没有办法做到这一点?
我这样尝试过:
Navigation.findNavController(ActivityBlue.newInstance(),R.id.host_navigation).navigate(R.id.blueFragmentTwo)
有什么建议吗?
答案 0 :(得分:0)
解决方案:
故意启动“活动”,并将目的地作为Intent extra
传递。
val blueIntent = Intent(requireActivity(), ActivityBlue::class.java)
blueIntent.putExtra("navigationStartDestination", R.id.blueFragmentTwo)
startActivity(blueIntent)
在ActivityBlue
onCreate
->中获取intent extra
并定义导航图
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
重要!
在navGraph="nav_graph_blue"
的布局xml中删除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" />