16

I'm trying to transition from using a FrameLayout to using FragmentContainerView and from the tutorials I've seen, it should be pretty easy. However, when I run my app after making the change, I get

Error inflating class androidx.fragment.app.FragmentContainerView
Caused by: java.lang.ClassNotFoundException: androidx.fragment.app.FragmentContainerView

my layout file is pretty simple:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="@layout/app_bar_main">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

Do I need to add something into my build.gradle or something? Why can't it find the class?

Randy
  • 1,068
  • 2
  • 14
  • 32
  • 4
    If it is happening only in release builds, then it is a pro-guard issue. Check this quick fix: https://stackoverflow.com/a/61365688/3484700 – Salam El-Banna Jul 12 '20 at 15:17

4 Answers4

35

That's in androidx.fragment 1.2.0 or higher:

implementation "androidx.fragment:fragment:1.2.0"
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
8

Thanks to @Salam El-Banna and his link, I found that in case an application crashes in release build we should add in proguard-rules.pro (one or two lines, depending on android:name in <FragmentContainerView>:

#-------------------------------------------------
# JetPack Navigation
# This fixes: 
# Caused by: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment androidx.navigation.fragment.NavHostFragment: make sure class name exists
# Caused by: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.google.android.gms.maps.SupportMapFragment: make sure class name exists
#-------------------------------------------------

-keepnames class androidx.navigation.fragment.NavHostFragment
-keepnames class com.google.android.gms.maps.SupportMapFragment
CoolMind
  • 26,736
  • 15
  • 188
  • 224
0

Make sure their are no custom constructors like this.
ex:

FragmentName (val ctx: Context): Fragment() {

change to

FragmentName: Fragment() {

The reason is when the inflater inflates FrgmentContainer, it calls default constructor to initialize the fragments. If their is no default constructor available, it will crash.

chris
  • 194
  • 2
  • 10
0

If you are using kotlin the latest FragmentContainerView implementation stays under:

implementation("androidx.fragment:fragment-ktx:1.3.6")
Nicola Gallazzi
  • 7,897
  • 6
  • 45
  • 64