3

Android Studio offers to replace a <fragment> tag in Google Maps fragment. In an application I don't have Navigation, but probably will add. Should I replace the <fragment> tag with <FragmentContainerView>?

enter image description here

Looking at https://proandroiddev.com/android-fragments-fragmentcontainerview-292f393f9ccf I found that we can also replace <FrameLayout> with <androidx.fragment.app.FragmentContainerView>. Should we do so?

CoolMind
  • 26,736
  • 15
  • 188
  • 224

2 Answers2

3

<FragmentContainerView... is meant to replace both <FrameLayout... and <Fragment... Refer to this answer on a similar question.

Answer on the benefit of using <FragmentContainerView

SABANTO
  • 1,316
  • 9
  • 24
  • Thanks! Looking at https://developer.android.com/reference/androidx/fragment/app/FragmentContainerView I understood, that we should replace `` in an activity, not in fragment. – CoolMind Oct 02 '20 at 11:56
1

Thanks to SABANTO I replaced <fragment> and <FrameLayout> with <androidx.fragment.app.FragmentContainerView> (replaced <FrameLayout> only in activities). It works right in debug build, but not in release where it crashes.

android.view.InflateException: Binary XML file line #16 in com.example:layout/fragment_show_map: Binary XML file line #16 in com.example:layout/fragment_show_map: Error inflating class androidx.fragment.app.FragmentContainerView
Caused by: android.view.InflateException: Binary XML file line #16 in com.example:layout/fragment_show_map: Error inflating class androidx.fragment.app.FragmentContainerView
Caused by: androidx.fragment.app.FragmentActivity$HostCallbacks: Unable to instantiate fragment com.google.android.gms.maps.SupportMapFragment: make sure class name exists
Caused by: java.lang.ClassNotFoundException: com.google.android.gms.maps.SupportMapFragment

Looking at ClassNotFoundException when using androidx.fragment.app.FragmentContainerView and https://stackoverflow.com/a/61365688/2914140 I found that we should add in proguard-rules.pro one or two lines, depending on what you have in XML file:

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    ...

proguard-rules.pro:

#-------------------------------------------------
# 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.FragmentActivity$HostCallbacks: 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

Don't forget to test your applications in release build (and in debug build, of course).

CoolMind
  • 26,736
  • 15
  • 188
  • 224