Fragment Lifecycle When Using add and Replace

We all have questions which methods are called when fragment is added or it is replaced by other fragment or when we press back from replaced or added fragment.

Today we will look at all important method called in fragment lifecycle when operation happen.

You can check about all lifecycle method with explanation on https://developer.android.com/guide/components/fragments

Here is brief chart about fragment lifecycle.

Fragment LifeCycle : Important Methods
Fragment LifeCycle : Important Methods

Source: https://developer.android.com/images/fragment_lifecycle.png

Add in ViewPager -> Replace -> Back -> Back

1. Activity -> Add Frag A ( Add Frag B in ViewPager inside A)

A -> onAttach : OnCreateView : OnViewCreated : onActivityCreated : onStart : onResume

B -> onAttach : onCreateView : onViewCreated : onActivityCreated : onStart : onResume

2. When C is Replaced in view pager

C -> onAttach  : B -> onPause : A -> onPause :  B -> onStop :  A -> onStop

B -> onDestroyView : A -> onDestroyView

C -> onCreateView : : OnViewCreated : onActivityCreated : onStart : onResume

3. On Back Pressed

C -> onPause : onStop : onDestroyView : onDestroy : onDetach

 A -> onCreateView : onViewCreated :onActivityCreated

 B -> onCreateView : onViewCreated :onActivityCreated

 A -> onStart :   B -> onStart :  A -> onResume  :  B -> onResume

4. On Back Pressed

B ->  onPause : A -> onPause :  B ->  onStop : A -> onStop

B ->  onDestroyView : A -> onDestroyView : B ->  onDestroy : B ->  onDetach

A -> onDestroy :A -> onDetach

Add in ViewPager -> Add -> Back -> Back

Start Activity -> Add Frag A ( Add Frag B in viewpager inside A)

A -> onAttach : OnCreateView : OnViewCreated : onActivityCreated : onStart : onResume

B -> onAttach : onCreateView : onViewCreated : onActivityCreated : onStart : onResume

Add Frag C

C -> onCreateView : : OnViewCreated : onActivityCreated : onStart : onResume

On BackPressed

C -> onPause : onStop : onDestroyView : onDestroy : onDetach

On BackPressed

B ->  onPause : A -> onPause :  B ->  onStop : A -> onStop

B ->  onDestroyView : A -> onDestroyView : B ->  onDestroy : B ->  onDetach

A -> onDestroy :A -> onDetach

We have learned about methods called when different fragment Operation. Please do let us know in case of you want more question like to be explored and answered.

We will be adding more cool stuff like this which help clear understanding of android fun .

Happy Learning.

Check out More Blogs on Android

http://marukhambhisar.com/blog/category/android/

One Reply to “Fragment Lifecycle When Using add and Replace”

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.