You need to know some premise before using FragmentManager.
in Activity
there is FragmentManager and we should call it with getSupportFragmentManager()
, getFragmentManager()
is deprecated.
in Fragment
there are multiple FragmentManagers called ParentFragmentManager
and ChildFragmentManager
, the final FragmentManager
which is deprecated too. And ParentFragmentManager
will be same as Activity's FragmentManager
getActivity().onBackPressed()
will pull out fragment if any stack exists in Activity's FragmentManager
fragmentManager.popBackStack()
will pull out fragment if any stack exists in Activity's or Fragment's FragmentManager rely on who calls
Base on above points
(1) If You want to hold fragments in Activity
, you should call getSupportFragmentManager()
in Activity, and call getParentManager()
in Fragment, then onBackPressed()
will pull out the fragment you last add to stack.
(2) If you want to hold fragments in a Fragment and Separated from Activity, you should call getChildFragmentManager()
in Fragment, then activity.onBackPressed()
will pull out the fragment which in Activity's fragment stack and ignore other fragments in Fragment's fragment stack.
For question will be same as case (1), and if you dont want re-create fragment, you should use add()
instead of replace()
in Fragment A
CertificateItemFragment certificateItemFragment = new CertificateItemFragment(item);
FragmentManager fragmentManager = getParentFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.nav_host_fragment, certificateItemFragment).addToBackStack(CertificateItemFragment.TAG);
fragmentTransaction.commit();
now onBackPressed()
will backstack from CertificateItemFragment to Pre-Fragment