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.

Android | Java | Kotlin | Full Stack Developer