Can't find method getFragment() in my FragmentContainerView object

Viewed 3093

In the XML I have

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/identifications_map_view"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:visibility="gone"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

I would like to get the Fragment from the View. The documentation suggests to use

FragmentContainerView fcv = findViewById(R.id.identifications_map_view);
SupportMapFragment smf = fcv.getFragment()

But Android Studio cannot resolve symbol, and if I CTRL+Click the "FragmentContainerView" it doesn't show getFragment() when i search with CTRL+F.

I know there is another way to get the Fragment but I was wondering why I can't do it this way. I guess there is some problem with the version, because I seem to have an older version of the class than the documentation's, for example there is also an extra constructor that uses the FragmentManager, nowhere to be found in the documentation. Could it even be minimum API problem? I have 24.

Thanks.

4 Answers

As stated by Sam, the method getFragment() wasn't added to FragmentContainerView until 1.4.0 alpha versions.

However, as per documentation:

This method grabs the Fragment whose view was most recently added to the container. This may used as an alternative to calling FragmentManager.findFragmentById and passing in the FragmentContainerView's id.

Therefore, the alternative here is to simply do it as you would with the <fragment /> tag:

SupportMapFragment smf = (SupportMapFragment) getSupportFragmentManager()
        .findFragmentById(R.id.identifications_map_view);

And things would work just as well.

When you use androidx.fragment.app.Fragment try this:

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/fragment_container"
    android:name="com.example.YourFragment"
    android:tag="custom_tag"
    tools:layout="@layout/your_fragment_layout" />

And get this fragment instance by:

childFragmentManager.findFragmentByTag("custom_tag")

UPD: In some cases it doesn't works. I don't know why. Try this:

binding.fragmentContainer.getFragment<YourFragment>()
Related