onDestroy() : onDestroy()
called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform.
(Called when the fragment is no longer in use, after onStop and before onDetach())
onDetach() : onDetach()
called after onDestroy()
, to notify that the fragment has been disassociated from its hosting activity. (Called when the fragment is no longer attached to its activity)
ref: android-fragment-lifecycle, onDestroy,onDetach
take a look at Fragment class (line 1564), performDestroy is called first if f.mRetaining is false :
if (DEBUG) Log.v(TAG, "movefrom CREATED: " + f);
if (!f.mRetaining) {
//performDestroy is called first if f.mRetaining is false, else not
f.performDestroy();
dispatchOnFragmentDestroyed(f, false);
} else {
f.mState = Fragment.INITIALIZING;
}
//then performDetach
f.performDetach();
dispatchOnFragmentDetached(f, false);
if (!keepActive) {
if (!f.mRetaining) {
makeInactive(f);
} else {
f.mHost = null;
f.mParentFragment = null;
f.mFragmentManager = null;
}
}
And here is the code of performDestroy and performDetach:
void performDestroy() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
if (mChildFragmentManager != null) {
mChildFragmentManager.dispatchDestroy();
}
mState = INITIALIZING;
mCalled = false;
mIsCreated = false;
onDestroy();
if (!mCalled) {
throw new SuperNotCalledException("Fragment " + this
+ " did not call through to super.onDestroy()");
}
mChildFragmentManager = null;
}
void performDetach() {
mCalled = false;
onDetach();
mLayoutInflater = null;
if (!mCalled) {
throw new SuperNotCalledException("Fragment " + this
+ " did not call through to super.onDetach()");
}
// Destroy the child FragmentManager if we still have it here.
// We won't unless we're retaining our instance and if we do,
// our child FragmentManager instance state will have already been saved.
if (mChildFragmentManager != null) {
if (!mRetaining) {
throw new IllegalStateException("Child FragmentManager of " + this + " was not "
+ " destroyed and this fragment is not retaining instance");
}
mChildFragmentManager.dispatchDestroy();
mChildFragmentManager = null;
}
}