The naming of the fragment management methods are very confusing even according to Google engineers on message boards (see comments above). I made myself a little demo to figure out how things actually work. Here are my findings. Feel free to correct me if I am wrong.
To initially add a Fragment to an Activity, you use:
getFragmentManager().beginTransaction().add(R.id.container, mFragment).commit().
This associates the Activity with the Fragment and also associates a View with the Fragment.
Here are the resulting life cycle events and other important method return values:
onAttach()
onCreate()
onCreateView()
onViewCreated()
onActivityCreated()
onViewStateRestored()
onStart()
onResume()
mFragment.getView() == null: false
mFragment.getActivity() == null: false
To remove a Fragment from an Activity, you use:
getFragmentManager().beginTransaction().remove(mFragment).commit().
This removes any association with a View or to an Activity.
Here are the resulting life cycle events and other important method return values:
onPause()
onStop()
onDestroyView()
onDestroy()
onDetach()
mFragment.getView() == null: true
mFragment.getActivity() == null: true
I re-added the fragment here
To detach an added Fragment from an Activity, you use:
getFragmentManager().beginTransaction().detach(mFragment).commit().
This removes any association with a View, but keeps the association with the Activity.
Here are the resulting life cycle events and other important method return values:
onPause()
onStop()
onDestroyView()
mFragment.getView() == null: true
mFragment.getActivity() == null: false
To re-attach a Fragment that was detached to the Activity, you use:
getFragmentManager().beginTransaction().attach(mFragment).commit().
This creates a new View to associate with the Fragment and maintains the Activity association.
Here are the resulting life cycle events and other important method return values:
onCreateView()
onViewCreated()
onActivityCreated()
onViewStateRestored()
onStart()
onResume()
mFragment.getView() == null: false
mFragment.getActivity() == null: false
Other important things to note:
If you detach a Fragment and then try to add it again using add() rather than attach(), nothing seems to change.
if you attempt to add a Fragment that has been removed using remove() by using attach() rather than add(), nothing seems to change.
When getView() returns null, the Fragment may still have internal references to the last View it created. This View is no longer valid and should not be used.
Fragment
is detached, itsonPause
,onStop
andonDestroyView
methods are called only (in that order). On the other hand, when aFragment
is removed, itsonPause
,onStop
,onDestroyView
,onDestroy
andonDetach
methods are called (in that order). Similarly, when attaching, theFragment
'sonCreateView
,onStart
andonResume
methods are called only; and when adding, theFragment
'sonAttach
,onCreate
,onCreateView
,onStart
andonResume
methods are called (in that order). – Extrorse