0

I need to create a specific behavior at some point in my app. I use a navigation drawer and I replace fragments in a frame layout.

Let's say I have some fragments in the backstack: A -> B -> C.
A is one of the root fragments in my app, if the back button is pressed on A, the app quits.

When I am on C (with A and B in the backstack) I want to go to E with D in the backstack. Meaning if I press the back button on E, I want to go to D (D being another root fragment in my app, if I press the back button on D the app quits).

For now I clear the back stack, then I replace the current fragment with D and then with E.
The problem with this is that I see the fragment A for a small amount of time during the transition from C to E. (And it's ugly right?)

grandouassou
  • 2,500
  • 3
  • 25
  • 60

2 Answers2

0

To avoid showing D during the transition from C to E, you can add a boolean which keeps track of whether it's the first time D was active. You check it in D's onActivityCreated; if it's the first time D was active (when you really want to show E), don't load the content, then flip the boolean, so that you know to load the content next time D is active.

Patricia Li
  • 1,346
  • 10
  • 19
  • I don't see D, I see A. Which is the result of clearing the backstack (B and C are removed). I'm looking for a way to do it properly. On iOS I would modify the NSNavigationController.viewControllers property. – grandouassou Nov 26 '14 at 22:42
-1

The first part you can do (C -> E with D on backstack). Simply add both to the same transaction:

getFragmentManager().beginTransaction()
    .add(R.id.container, FragmentD.newInstance())
    .add(R.id.container, FragmentE.newInstance())
    .addToBackStack(null)
    .commit();

And then you will transition smoothly to E without seeing D, but D will be on the backstack beneath E.

Unfortunately there is no way to remove items from the backstack other than popping them from the stack (you can't remove something from the bottom of the stack).

Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274
  • I was reviewing my questions without accepted answers and though I was not the one who downvoted your answer, I don't think this would work. You're adding 2 fragments in the same transaction. Going back would remove the 2 fragments at the same time. Right? – grandouassou Sep 01 '15 at 19:51