There is not any need to get the FragmentManager
directly from the Activity
because a replacement method has been provided in the Fragment
called getParentFragmentManager
:
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
From the docs for the deprecated getFragmentManager
:
* @deprecated This has been removed in favor of <code>getParentFragmentManager()</code> which
* throws an {@link IllegalStateException} if the FragmentManager is null. Check if
* {@link #isAdded()} returns <code>false</code> to determine if the FragmentManager is
* <code>null</code>.
The docs for the replacement method getParentFragmentManager
:
* Return the FragmentManager for interacting with fragments associated
* with this fragment's activity. Note that this will available slightly
* before {@link #getActivity()}, during the time from when the fragment is
* placed in a {@link FragmentTransaction} until it is committed and
* attached to its activity.
*
* <p>If this Fragment is a child of another Fragment, the FragmentManager
* returned here will be the parent's {@link #getChildFragmentManager()}.
*
* @throws IllegalStateException if not associated with a transaction or host.
Just take care to check isAdded
to make sure that the FragmentManager
is not null.