You need to add fragments to the backstack as follows: -
FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.content_frame, fragmentA); //No need to put fragment A in backstack ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.content_frame, fragmentB); ft.addToBackStack(null); ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.content_frame, fragmentC); ft.addToBackStack(null); ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.content_frame, fragmentD); ft.addToBackStack(null); ft.commit();
Now all your fragments are in the back of the screen, therefore, if you click "Back on the fragment", then the fragment "C" will be shown and after clicking "Back" in the fragment C, fragment B will be shown, and when you click "Back" in the fragment B will display fragment A.
AS, you mentioned that you have a special button in fragment D, which when pressed should take you to fragment A, so when you click this button, execute this code: -
FragmentManager fm = getActivity().getSupportFragmentManager(); for(int i = 0; i < fm.getBackStackEntryCount(); ++i) { fm.popBackStack(); }
source share