导航至 Android 上的嵌套导航图时收到的参数为空
Arguments received as null while navigating to nested nav graph on Android
下面是带有嵌套导航图的 app_nav_graph.xml
的代码:
<navigation
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/app_nav_graph"
app:startDestination="@id/homeFragment">
<include app:graph="@navigation/nested_nav_graph" />
<fragment
android:id="@+id/homeFragment"
android:name="com.sd.android.ui.HomeFragment">
<action
android:id="@+id/action_homeFragment_to_nestedNavGraph"
app:destination="@id/nested_nav_graph" />
</fragment>
</navigation>
这里是nested_nav_graph.xml
:
<navigation
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nested_nav_graph"
app:startDestination="@id/nestedHomeFragment">
<fragment
android:id="@+id/nestedHomeFragment"
android:name="com.sd.android.ui.NestedHomeFragment">
</fragment>
</navigation>
这里是放置在 HomeActivity
中的导航代码(托管 NavHostFragment):
navController.setGraph(R.navigation.app_nav_graph);
Bundle bundle = new Bundle();
bundle.putInt("key", 1);
navController.navigate(R.id.action_homeFragment_to_nestedNavGraph);
问题是 NestedHomeFragment
没有收到传递的包,即 getArguments()
正在返回 null
。
为什么会这样?有什么解决这个问题的建议吗?
谢谢
在您的代码中,您正在创建 Bundle
,但实际上并未将其传递给对 navigate()
的调用。您需要这样做才能将其实际发送到您的目的地:
Bundle bundle = new Bundle();
bundle.putInt("key", 1);
navController.navigate(R.id.action_homeFragment_to_nestedNavGraph, bundle);
下面是带有嵌套导航图的 app_nav_graph.xml
的代码:
<navigation
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/app_nav_graph"
app:startDestination="@id/homeFragment">
<include app:graph="@navigation/nested_nav_graph" />
<fragment
android:id="@+id/homeFragment"
android:name="com.sd.android.ui.HomeFragment">
<action
android:id="@+id/action_homeFragment_to_nestedNavGraph"
app:destination="@id/nested_nav_graph" />
</fragment>
</navigation>
这里是nested_nav_graph.xml
:
<navigation
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nested_nav_graph"
app:startDestination="@id/nestedHomeFragment">
<fragment
android:id="@+id/nestedHomeFragment"
android:name="com.sd.android.ui.NestedHomeFragment">
</fragment>
</navigation>
这里是放置在 HomeActivity
中的导航代码(托管 NavHostFragment):
navController.setGraph(R.navigation.app_nav_graph);
Bundle bundle = new Bundle();
bundle.putInt("key", 1);
navController.navigate(R.id.action_homeFragment_to_nestedNavGraph);
问题是 NestedHomeFragment
没有收到传递的包,即 getArguments()
正在返回 null
。
为什么会这样?有什么解决这个问题的建议吗?
谢谢
在您的代码中,您正在创建 Bundle
,但实际上并未将其传递给对 navigate()
的调用。您需要这样做才能将其实际发送到您的目的地:
Bundle bundle = new Bundle();
bundle.putInt("key", 1);
navController.navigate(R.id.action_homeFragment_to_nestedNavGraph, bundle);