如果在Fragment.onCreate()中引用Activity.onCreate()创建的对象,可能会抛空指针异常,这是因为Fragment.onCreate()可能会在Activity.onCreate()没执行完时就执行了,一般出现在Activity销毁再重建的情况下,这个时候可以把Fragment.onCreate()中的引用搬到Fragment.onActivityCreated()中。
FragmentActivity中onCreate()执行到最后会调用mFragments.dispatchCreate(),该方法实际上会调到FragmentManager.moveToState(),从而调到Fragment.performCreate(),这个方法中就会直接调Fragment.onCreate()。
@SuppressWarnings("deprecation")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
mFragments.attachHost(null /*parent*/);
super.onCreate(savedInstanceState);
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
mFragments.restoreLoaderNonConfig(nc.loaders);
}
if (savedInstanceState != null) {
Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
mFragments.restoreAllState(p, nc != null ? nc.fragments : null);
}
mFragments.dispatchCreate();
}
public void dispatchCreate() {
mStateSaved = false;
moveToState(Fragment.CREATED, false);
}
void moveToState(Fragment f, int newState, int transit, int transitionStyle,
boolean keepActive) {
...
if (!f.mRetaining) {
f.performCreate(f.mSavedFragmentState);
}
...
}
void performCreate(Bundle savedInstanceState) {
...
onCreate(savedInstanceState); // fragment中的onCreate()
...
}