java – Skipping a fragment while walking on the back stack

Question:

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 fragment C, you need to skip fragment B and return directly to A.

I was looking for info for a long time, either the problem statement is different and the solution is not suitable, or they suggest calling popBackStack twice in a row, which, in my opinion, is terrible, and I need to skip the B franment just programmatically, and not visually, so that the user does not notice.

The code is below.

Fragment A , calling fragment B:

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 , calling 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 the Activity host, handling the Back key press:

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

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

Thank you.

Answer:

This is how you can rollback transactions to the fragment with the specified tag:

fragmentManager.popBackStackImmediate(fragmentName, 0);

That is, if you specify fragmentName in onBackPressed equal to the tag of the phrase A, then it should appear instead of B.

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

Scroll to Top