Using Fragments in your application is a very good practise that makes the application more responsive and transitive in the sense that it looks a bit fast. But sometimes it becomes a problem to manage these fragments. Now to differentiate the two main functions in fragments i.e popBackStack() and replace(), lets take two fragments, Fragment (A) and Fragment (B).
Now the replace() performs two things:-
- Remove currently added fragment (A) from the container (C) you indicated.
- Add new fragment (B) to the same container.
These 2 operations are what is saved as a Backstack record / transaction.
Note that fragment A remains in created state, but its view is destroyed.
Now popBackStack() reverses your last transaction that you've performed through replace().
In this case that would be 2 steps:
- Remove fragment (B) from container (C).
- Add fragment (A) to container C.
After this, fragment B becomes detached, and if you did not keep references to it, it will be garbage collected.
Now it is important to understand that you don't actually add Fragments to Backstack, you add FragmentTransactions. So when you think that you are doing "replace with Fragment B, and adding Fragment A to the back stack", then you actually add this whole operation to backstack - that is- remove A and add B.
Then, next step is popping of the transaction that contains this replacement. So you're not popping FragmentA, you're reversing the above transaction "remove A, add B", which when reversed is "remove B, add A".
So after this - there's no fragment (B) that the FragmentManager is aware of, so when you add it by replacing A with B at the above step, B needs to go through its early lifecycle methods - onAttach() and onCreate().
That's all, enjoy.!! and always code to make it better..!!
No comments:
Post a Comment