I've encountered some curious behavior in my application when managing Fragments and I was wondering if SO could help shed some light onto why this happens.
I have two Fragments, we'll call them Fragment A and Fragment B. The general flow of my application is that when the user interacts with Fragment A in some way, Fragment B is shown by calling fragmentTransaction.replace()
(this happens in all cases). When I show Fragment B, I add Fragment A to the back stack; then, when the user presses the back button on Fragment B, Fragment A gets shown again by popping from the back stack.
That's all well and good, but today I discovered that there is a flow from Fragment B which calls fragmentTransaction.replace()
, replacing Fragment B with the same instance of Fragment A that is currently on the back stack.
In and of itself there's nothing wrong with that, however the strange behavior arises when I go back from Fragment A into Fragment B. If I called fragmentTransaction.replace()
, the onCreate()
method of Fragment B is not called.
However, if I popped Fragment A from the back stack and then replaced it with Fragment B, the onCreate()
method of Fragment B is fired. Why is this?
Note that all instances of Fragment A and Fragment B are created at the time their host Activity is launched.
Edit for clarification. The case where onCreate()
is called a second time is the following: Attach Fragment A => replace with Fragment B, adding Fragment A to the back stack => pop Fragment A using popBackStack()
=> replace Fragment A with Fragment B again.