Fragment LifeCycle

Sohan Gupta
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.

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()

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

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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sohan Gupta
Sohan Gupta

Written by Sohan Gupta

Android | Java | Kotlin | Full Stack Developer

Responses (1)

Write a response