There are 3 fragments: A, B, C.

All are hosted on one Activity , from A I call B, then from B I call C (A -> B -> C).

When you press the "back" button in the fragment C, you must skip the fragment B and return immediately to A.

I have been looking for information for a long time, either posing the problem is different and the solution is not suitable, or they suggest calling popBackStack two times in a row, which, in my opinion, is terrible, and I need to skip program B exactly programmatically, not visually, so that the user doesn’t notice.

Code below.

Fragment A , Fragment B call:

 this.mFuelCardAuthBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainFragment.this.getActivity().getFragmentManager() .beginTransaction() .replace(R.id.activity_main_fragment_container, AuthProgressFragment.newInstance()) .addToBackStack(MainFragment.class.getSimpleName()) .commit(); } }); 

Fragment B , invocation of fragment C:

 this.getActivity().getFragmentManager().beginTransaction() .replace(R.id.activity_main_fragment_container, AuthSuccessFragment.newInstance(AppConst.FUEL_CARD_AUTH_TYPE)) .addToBackStack(AuthProgressFragment.class.getCanonicalName()) .commit(); 

In an Activity host, the handling of pressing the Back key:

 @Override public void onBackPressed() { if (this.getFragmentManager().getBackStackEntryCount() > 1) { this.getFragmentManager().popBackStack(); } else { super.onBackPressed(); } } 

In general, there is a feeling that the return processing for back is not implemented correctly for me, although it works, so I would be grateful if you send it to the right path in this topic.

Thank.

    1 answer 1

    This is how you can roll back transactions to a fragment with the specified tag:

     fragmentManager.popBackStackImmediate(fragmentName, 0); 

    Ie if in onBackPressed you specify fragmentName equal to the tag of fraction A, then it will have to appear instead of B.

    In theory, with a crutch you can check the number of fragments in the manager, and if there are more than 2, then call it, otherwise super

    • it would be good if it were so, only this is not so and this (the most obvious and, in theory, the correct option) does not work, fragment B is still invoked. It is possible that the matter is in handling the onBackPressed event in the Activity, therefore I asked to pay attention to this. - Alexander Lomovskiy
    • Besides, if I don’t add fragment B to the stack, then when I press the Back button in fragment B, I exit the application, but I need to go back to fragment A. Such a pain .. - Alexander Lomovskiy
    • @AlexanderLomovskiy. Updated the answer. It is necessary And also to add with the tag and roll back to this transaction if there are more than 2 fragments in the manager - YuriySPb