KennySon
KennySon

Reputation: 39

Which method will call when user press back with add Fragment method (not replace fragment)

I am looking for an answer but could not find for the following.

So my question is, which method in fragment A will be called when fragment B is detached, I am debugging all onResume, onAttach in fragment A, but looks like it is not called.

one point that if we using replace fragment instead of add fragment, it will run extract with the fragment lifecycle, but with "add" method, look like fragment A still visible on screen, so anyway to detect when fragment A not being overlay by Fragment B any more?

Any ideas?

Upvotes: 0

Views: 1954

Answers (2)

corda dev
corda dev

Reputation: 169

When user navigate one activity to fragment then below life cycle called

FirstFragment: onAttach

FirstFragment: onCreate

FirstFragment: onCreateView

FirstFragment: onViewCreated

FirstFragment: onActivityCreated

FirstFragment: onStart

FirstFragment: onResume

when user navigate firstfragment to second fragment in case of addtobackstack and add() then below life cycle called SecondFragment: onAttach

SecondFragment: onCreate

SecondFragment: onCreateView

SecondFragment: onViewCreated

SecondFragment: onActivityCreated

SecondFragment: onStart

SecondFragment: onResume

when user pressed back in case of addtobackstack() and add() then below life cycle called SecondFragment: onPause

SecondFragment: onStop

SecondFragment: onDestroyView

SecondFragment: onDestroy

SecondFragment: onDetach

when user navigate firstfragment to second fragment in case of addtobackstack and replace() then below life cycle called SecondFragment: onAttach

SecondFragment: onAttachonAttach

SecondFragment: onCreate

FirstFragment: onPause

FirstFragment: onStop

FirstFragment: onDestroyView

SecondFragment: onCreateView

SecondFragment: onViewCreated

SecondFragment: onActivityCreated

SecondFragment: onStart

SecondFragment: onResume

when user pressed back in case of addtobackstack() and replace then below life cycle called SecondFragment: onPause

SecondFragment: onStop

SecondFragment: onDestroyView

SecondFragment: onDestroy

SecondFragment: onDetach

FirstFragment: onCreateView

FirstFragment: onViewCreated

FirstFragment: onActivityCreated

FirstFragment: onStart

FirstFragment: onResume

Upvotes: 6

KennySon
KennySon

Reputation: 39

Finally, I found the way to handle in the case of "add fragment" (Please notice when we use add fragment, the fragment lifecycle is not run like "replace fragment").

In Activity just implement FragmentManager.OnBackStackChangedListener to handle when back stack is changed, and then get the top fragment of the back stack to do what you want.

Upvotes: 0

Related Questions