我试图了解Android片段的内部行为。怀疑onDestroy()
,onDetach()
和
void onDestroy ()
在不再使用该片段时调用。在onStop()
之后和onDetach().
之前调用
void onDetach ()
当片段不再附加到其活动时调用。这是在onDestroy()之后调用的。
查询: 如果不再使用该片段,是否意味着我们可以从“活动”中删除该片段了?
在这种情况下,为什么要先调用onDestroy()然后再调用onDetach(),我们只能使用一种方法来指示“片段不再使用,可以删除活动”的状态
答案 0 :(得分:0)
onDestroy():onDestroy()
被调用以对片段的状态进行最终清理,但不能保证被Android平台调用。
(在片段不再使用时,在onStop之后和onDetach()之前调用)
onDetach():onDetach()
在onDestroy()
之后调用,以通知该片段已从其宿主活动中脱离。 (当片段不再连接到其活动时调用)
ref :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;
}
}
答案 1 :(得分:0)
如果您研究了整个片段的生命周期,那么
onAttach() onCreate()
对应
onDetach() onDestroy()
生命周期方法。 因此为了不破坏设计一致性生命周期方法的调用顺序如下
onAttach()
onCreate()
onDestroy()
onDetach()
现在让我们继续您的查询
查询:如果不再使用该片段,则意味着我们可以从“活动”中删除该片段了?
在这种情况下,为什么要先调用onDestroy()然后再调用onDetach(),我们只能使用一种方法来指示“片段不再使用,可以删除活动”的状态
Android始终尝试维护其对应版本。您的查询的答案为什么onAttached首先给出您查询的答案
片段被设计为与活动无关。onAttach()提供一个接口,用于在初始化片段之前参考片段确定包含活动的状态/类型/(与片段有关的其他详细信息)。< / p>