Accessing in a Fragment Inside a fragment, you can get a reference to the FragmentManager that manages the fragment's children through getChildFragmentManager() . If you need to access its host FragmentManager , you can use getParentFragmentManager() .
getSupportFragmentManager and getChildFragmentManager FragmentManager is class provided by the framework which is used to create transactions for adding, removing or replacing fragments. getSupportFragmentManager is associated with Activity consider it as a FragmentManager for your Activity .
To get the current fragment that's active in your Android Activity class, you need to use the supportFragmentManager object. The supportFragmentManager has findFragmentById() and findFragmentByTag() methods that you can use to get a fragment instance.
You can directly call
getFragmentManager()
to get the fragment manager.
or
In your fragment,
Create field :
private FragmentActivity myContext;
override onAttach method of your fragment :
@Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
When you need to get Support fragment manager call :
FragmentManager fragManager = myContext.getSupportFragmentManager(); //If using fragments from support v4
or
FragmentManager fragManager = myContext.getFragmentManager();
You are done.
All you need to do is using
getFragmentManager()
method on your fragment. It will give you the support fragment manager, when you used it while adding this fragment.
Fragment Documentation
Simply get it like this -
getFragmentManager() // This will also give you the SupportFragmentManager or FragmentManager based on which Fragment class you have extended - android.support.v4.app.Fragment OR android.app.Fragment.
OR
getActivity().getSupportFragmentManager();
in your Fragment's onActivityCreated() method and any method that is being called after onActivityCreated().
Kotlin users try this answer
(activity as AppCompatActivity).supportFragmentManager
if you have this problem and are on api level 21+ do this:
map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
.getMap();
this will get the map when used inside of a fragment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With