gdaramouskas
gdaramouskas

Reputation: 3747

Android fragments move through the stack

Imagine this: One activity with 5 fragments.

Fragment1 -> Fragment2 (fragment1 opens fragment2 and onBackPressed reverses the operation)

Fragment3 -> Fragment4

This works as expected but now I want to do this:

Fragment5 -> Fragment4 which works but when I press the onBackPressed() I want to be taken to Fragment3 not Fragment5. And when I get to Fragment3 and press back to exit the app.

I tried to do many things in order to manipulate the backstack. But none of these resolves my problem. I swap the fragments via transaction.replace(container,myFragment).

I've checked the documentation provided, but I cannot seem to find a proper way to manipulate the backstack (or a flag whatsoever)

Upvotes: 1

Views: 130

Answers (1)

Machado
Machado

Reputation: 14489

You're switching betweens Fragments inside the same Activity.

All the FragmentTransaction are addToBackStack before commit. That means you can get how many times the user changed between the Fragments using the following method:

int count = getFragmentManager().getBackStackEntryCount();

In a way you can identify every Fragment and do whatever you want.

If you use the solution below you'll notice that getFragmentManager().popBackStack(); simply makes it return to the previous Fragment.

@Override
public void onBackPressed() {

    int count = getFragmentManager().getBackStackEntryCount();

    if (count == 0) {
        super.onBackPressed();
        //additional code
    } else {
        getFragmentManager().popBackStack();
    }

}

Upvotes: 1

Related Questions