Sitemap

Fragment LifeCycle

2 min readMar 16, 2021

--

Fragment has its own lifecycle. When a user navigates and interacts with your app, your fragments transition through various states in their lifecycle as they are added, removed, and enter or exit the screen.

Press enter or click to view image in full size
Fragment Life Cycle Diagram

Fragment callbacks while adding a fragment to another

Let’s assume we have two fragments A and B. Fragment A is already attached with an activity and have to add fragment B on top of fragment A.

FragmentB fb=new FragmentB();
getSupportFragmentManager().beginTransaction().add(R.id.frame_lay,fb).addToBackStack(null).commit();

Fragment B’s lifecycle methods will call only, no method of fragment A.

onAttach() -> onCreate() -> onCreateView() -> onActivityCreated() -> onStart() -> onResume()

Get Sohan Gupta’s stories in your inbox

Join Medium for free to get updates from this writer.

What happens when press back key button on above situation: Again fragment B’s lifecycle methods will call only, no method of fragment A.

onPause() -> onStop() -> onDestroyView() -> onDestroy() -> onDetach()

Fragment callbacks while replacing existing fragment with another

Let’s assume we have two fragments A and B. Fragment A is already attached with an activity and replacing fragment A by fragment B.

FragmentB fb=new FragmentB();
getSupportFragmentManager().beginTransaction().replace(R.id.frame_lay,fb).addToBackStack(null).commit();

Now both fragments lifecycle methods will invoke here, see below diagram with the sequence of methods

Press enter or click to view image in full size

What happens when press back key button on fragment B: Again both fragments lifecycle methods will invoke.

Press enter or click to view image in full size

--

--

Sohan Gupta
Sohan Gupta

Written by Sohan Gupta

Android | Java | Kotlin | Full Stack Developer