<androidx.fragment.app.FragmentContainerView> vs <fragment> as a view for a NavHost

Dmytro Karataiev picture Dmytro Karataiev · Nov 6, 2019 · Viewed 15.7k times · Source

When using androidx.fragment.app.FragmentContainerView as a navHost instead of a regular fragment app is not able to navigate to a destination after orientation change.

I get a following error: java.lang.IllegalStateException: no current navigation node

Is there a gotcha that I should know about to use it properly or is my way of using nav components is incorrect?

Simple activity xml with a view:


...
    <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" />
...

Navigation code:

<?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>

Here is a github repo where you can easily reproduce a bug: https://github.com/dmytroKarataiev/navHostBug

Answer

ianhanniballake picture ianhanniballake · Nov 6, 2019

The no current navigation node error occurs when there's no graph set and you attempt to call navigate(). If it only occurs when you're using FragmentContainerView and after a configuration change, then this would be related to this bug, which is fixed and scheduled for release with Navigation 2.2.0-rc03.

To work around this issue, you can either switch back to <fragment> or remove app:navGraph="@navigation/nav_simple" and instead call navController.setGraph(R.navigation.nav_simple).