5

I want to avoid that in this navigation use case: A -> B -> A -> B -> A -> B ...

Where all the fragment instances are kept in the back stack. Reason: Avoid out of memory error.

I tried creating an own navigation workflow, like described here: https://stackoverflow.com/questions/18041583/fragments-backstack-issue?noredirect=1#comment26393904_18041583 (which is supposed to mimic activity behaviour calling always finish() after starting a new one, together with letting only the very first one (home) in the navigation stack). But it seems to be either very wrong or ununderstandable.

So I thought, also, to implement a behaviour like activity "bring to front" flag. But I don't know how to do it. Maybe something with popBackStack - but I don't know how to ask the fragment if the transaction already is in the backstack. And I don't know if I'm on the right path.

This should be a quite standard task, since every navigation menu basically has this problem. But still, seems not to be straight forward to implement, and also can't find information about it.

Any idea?

Community
  • 1
  • 1
User
  • 31,811
  • 40
  • 131
  • 232

1 Answers1

0

Take a look at the FragmentManager backstack. It has facilities for looking at/popping entries in the fragment backstack. You might want logic something along the lines of: if the user is asking for a fragment that is at the top of the stack (the previous fragment) then exit this fragment (go back) otherwise start a new one.

That would produce:

A (user asks for B)
A->B (user asks for A again)
A

.. but would not prevent

A (user asks for B)
A->B (user asks for C)
A->B->C (user asks for A)
A->B->C->A

That would require rewinding the stack back to "A" from "C", which you can do.. but then if that is the case, perhaps you should be unconditionally popping the fragment stack before starting a new fragment (I.E. No back stack at all..)

C B J
  • 1,838
  • 16
  • 22
  • Well, concerning your last sentence, that's what I tried before (linked in my post) but it's quite troublesome / doesn't work. For now I just reenabled the default stack behaviour - it will add as many instances as the user navigates to. But I'll come back to this with more time... – User Aug 04 '13 at 13:52