onDestroy():onDestroy()
调用以对片段的状态进行最终清理,但不保证会被 Android 平台调用。
(在片段不再使用时调用,在 onStop 之后和 onDetach() 之前)
onDetach():onDetach()
在 之后调用onDestroy()
,以通知片段已与其托管活动解除关联。(当片段不再附加到其活动时调用)
参考:android-fragment-lifecycle,onDestroy,onDetach
看一下 Fragment 类(第 1564 行),如果 f.mRetaining 为 false,则首先调用 performDestroy:
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;
}
}
这里是 performDestroy 和 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;
}
}