I created a demo to understand which fragment life cycle methods are invoked in different cases of a fragment transaction. Although most of the calls are waiting for a few things that I still confuse that I wrote in Bold.
Suppose that there are two fragments A and B, and we perform a transaction between them
Case 1
When fragment B is added to fragment A
getActivity().getSupportFragmentManager().beginTransaction().add(R.id.container, fragementB).addToBackStack(null).commit();
Fragment B
onAttach
Oncreate
onCreateView
onActivityCreated
Onstart
onResume
Fragment A life cycle methods are not used.
What did I expect?
the onStop method of fragment A is called because fragment A is not displayed
According to the documentation -
Stopped - the fragment is not displayed. Either the host activity was stopped or the fragment was removed from the activity, but added to the rear stop. The stopped fragment is still alive (all state and member information is saved by the system). However, it is no longer visible to the user and will be killed if killed.
Does this mean that no method of the current fragment is called when a new fragment is added to one activity?
Then using popBackStack()
in fragment B
Fragment B
Onpause
Onstop
onDestroyView
Ondestroy
onDetach
No fragment A life cycle methods are called
What did I expect?
the onStart method of fragment A is called because fragment A is now displayed
Case 2
When fragment B replaces fragment A
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, fragementB).commit();
Fragment B
onAttach
Oncreate
onCreateView
onActivityCreated
Onstart
onResume
Fragment A
Onpause
Onstop
onDestroyView
Ondestroy
onDetach
Everything was as expected
Case 3
When fragment B replaces fragment A while holding it in backstack
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, fragementB).addToBackStack("tag").commit();
Fragment B
onAttach
Oncreate
onCreateView
onActivityCreated
Onstart
onResume
Fragment A
Onpause
Onstop
onDestroyView
onDestroy and the onDetach method of fragment A are NOT called. Why is it not called? Bcoz according to the documentation method replace
removes all fragments that are already in the container and adds your new to the same container
Then using popBackStack()
in fragment B
Fragment A
onCreateView
onActivityCreated
Onstart
onResume
Fragment B
Onpause
Onstop
onDestroyView
Ondestroy
onDetach