Saehun Sean Oh Saehun Sean Oh - 1 year ago 79
Android Question

How to properly pop fragment in Android?

Current set up

+-> Activity1
| -> FragmentA
| -> FragmentB -+
| |
+- Activity2 <-------+

So Activity1 opens up FragmentA, FragmentB opens Activity2.
Then when Activity2 finishes, it comes back to Activity1 (no
. Just

I want to kill FragmentA and FragmentB when I go to Activity2, but when I do it, they get popped too fast so I can see my Activity1 running split second before Activity2 shows up.

--- What I tried ---

I tried to kill the fragments with Activity2, but now it's too slow so when I come back from Activity2 to 1, I can see the fragments lingering around.

Currently only working solution is put the clearing method into a
handler, but I don't like this solution because you can never know how much delay is enough

--- Why not kill it from Activity2? ---

I tried it with some hope, but fragmentManager doesn't allow me to pop backstack within different Activity, thus throws
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

Any suggestion?


Answer Source

I solved it by moving those fragments under Activity1a

So now it looks like this

+-> Activity1  --------+ 
|                      |
|   Activity1a  <------+
|   |   -> FragmentA
|   |   -> FragmentB
|   +-----------------------+
|                           |
+-- Activity2  <------------+

Activity1a is now an invisible Activity that holds on to FragmentA and B. When I want to transition to Activity2, now I just need to finish() from Activity1a, then all fragments attached to Activity1a will be gone.

From Android official document:

A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments.

This solved the problem. I just needed to handle corner cases like how onBackPressed() and such are used.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download