Darshan Kapasi
Darshan Kapasi

Reputation: 217

Fragment's onDestroyView not called on back button press

I have three Fragments in my application: Fragment A, B and C.

Steps:

  1. I am replacing A by B and keeping A in backstack.
  2. I am replacing B by C and not keeping B in backstack.
  3. I am pressing back button, on pressing back button A's onCreateView and then onStart is called (as it is on back stack)

The problem is Fragment C's onStop, onDestroyView etc are not called and thus Fragment A is not visible on the screen and Fragment C is visible (as it;s view is not destroyed).

Upvotes: 0

Views: 3730

Answers (2)

Mimmo Grottoli
Mimmo Grottoli

Reputation: 5773

I believe there is some misunderstanding of the back stack. When you replace A with B, you put the transaction A->B in the back stack, not the A fragment. The back stack knows that when the user presses the back button, it will have to rollback the transaction: destroy B and recreate A. In your case, you are replacing C with B and you're pressing back button: A will be recreated and B cannot be destroyed since it doesn't exist. Maybe you can find a solution listening for back stack events using FragmentManager.addOnBackStackChangedListener(), but I don't know if it fits your requirement.

Upvotes: 3

m0rpheu5
m0rpheu5

Reputation: 600

Please go through dev blog http://developer.android.com/guide/components/fragments.html

Fragments lifecycle is affected by Activity lifecycle.

Upvotes: 1

Related Questions