Replace fragment tag with FragmentContainerView Causing Runtime Error

Because it fails to find navigation controller in your activity class

Vincent Tsen
2 min readDec 24, 2021

You have fragment defined in your main activity layout xml file.

<fragment
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:navGraph="@navigation/nav_graph" />

Android studio gives you the following warning.

Replace the tag with FragmentContainerView.

You follow the suggestion and replace it with androidx.fragment.app.FragmentContainerView

<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:navGraph="@navigation/nav_graph" />

Then, you can build the project successfully. However, when you run it, your app crashes with the following run-time error.

Caused by: java.lang.IllegalStateException: Activity

--

--