How to avoid multiple instances of a fragment in the background stack?

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

Where all instances of the fragment are stored in the background stack. Reason: Avoid memory errors.

I tried to create my own navigation workflow, as described here: https://stackoverflow.com/questions/18041583/fragments-backstack-issue?noredirect=1#comment26393904_18041583 (which should simulate an activity behavior that invokes always finish () after starting a new one , and also allow only the first (home) in the navigation stack). But it seems very wrong or incomprehensible.

Therefore, I also thought about implementing such behavior as activity “lead to the front”. But I do not know how to do this. Maybe something is with popBackStack, but I don't know how to request a fragment if the transaction is already in the back. And I don’t know if I am on the right track.

This should be a fairly standard task, as every navigation menu has this problem. But still it seems that this is not so easy to implement, and also can not find information about it.

Any idea?

+4
source share
1 answer

Look at the stack of FragmentManager. It has the ability to search / record records in a stack of fragments. You may need some logic, for example: if the user requests a fragment located at the top of the stack (previous fragment), exit this fragment (go back), otherwise create a new one.

This will create:

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

.. but it doesn’t hurt

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

This will require rewinding the stack back to “A” from “C,” which you can do .. but then if so, you should probably unconditionally pop out the fragment stack before starting a new fragment (IE No back stack in general ..)

0
source

Source: https://habr.com/ru/post/1495179/


All Articles