当使用 androidx.fragment.app.FragmentContainerView
作为 navHost 而不是常规 fragment
方向更改后,应用程序无法导航到目的地。
我收到以下错误: java.lang.IllegalStateException: no current navigation node
是否有我应该知道的关于正确使用它的陷阱,或者我使用导航组件的方式不正确?
带有视图的简单活动 xml:
...
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
app:navGraph="@navigation/nav_simple" />
...
导航代码:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_legislator.xml"
app:startDestination="@id/initialFragment">
<fragment
android:id="@+id/initialFragment"
android:name="com.example.fragmenttag.InitialFragment"
android:label="Initial Fragment"
tools:layout="@layout/initial_fragment">
<action
android:id="@+id/action_initialFragment_to_destinationFragment"
app:destination="@id/destinationFragment" />
</fragment>
<fragment
android:id="@+id/destinationFragment"
android:name="com.example.fragmenttag.DestinationFragment"
android:label="Destination Fragment"
tools:layout="@layout/destination_fragment" />
</navigation>
这是一个 github 存储库,您可以在其中轻松重现错误: https ://github.com/dmytroKarataiev/navHostBug
原文由 Dmytro Karataiev 发布,翻译遵循 CC BY-SA 4.0 许可协议
no current navigation node
错误发生在没有图形集并且您尝试调用navigate()
。如果它仅在您使用FragmentContainerView
并且在配置更改后发生,那么这将与 此错误 有关,该错误已修复并计划与 Navigation 2.2.0-rc03 一起发布。要解决此问题,您可以切换回
<fragment>
或删除app:navGraph="@navigation/nav_simple"
并改为调用navController.setGraph(R.navigation.nav_simple)
。