根据class name创建Fragment实例,在这个方法里 也会调用fragment的无参构造函数,如果args不等于null,给mArguments 赋值,可以通过getArguments()获取。
publicstatic Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
try {
Class<?> clazz = sClassMap.get(fname);//先从sClassMap缓存里查找对应的class,如果没有,通过classloader去加载,并放入缓存if (clazz == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = context.getClassLoader().loadClass(fname);
sClassMap.put(fname, clazz);
}
Fragment f = (Fragment)clazz.newInstance();//调用无参构造函数创建一个实例if (args != null) {
args.setClassLoader(f.getClass().getClassLoader());
f.mArguments = args;//赋值
}
return f;
} catch (ClassNotFoundException e) {
thrownew InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (java.lang.InstantiationException e) {
thrownew InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (IllegalAccessException e) {
thrownew InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
}
}
调用这个方法来保存实例状态,如果fragment会被重新创建,outState会被传入onCreate(Bundle),onCreateView(LayoutInflater, ViewGroup, Bundle),onActivityCreated(Bundle)中。
这个方法相当于Activity的onSaveInstanceState(Bundle)方法。这个方法可以在onDestroy()之前的任一时刻被调用,有很多情况都可以导致fragment被销毁(例如fragment被放到回退栈的时候),它的状态不会被保存,除非activity需要保存。
public void onSaveInstanceState(Bundle outState) {
}
状态恢复,
finalvoid restoreViewState(Bundle savedInstanceState) {
if (mSavedViewState != null) {
mInnerView.restoreHierarchyState(mSavedViewState);
mSavedViewState = null;
}
mCalled = false;
onViewStateRestored(savedInstanceState);//子类可以重写这个方法来进行数据的恢复,必须调用父类的onViewStateRestored方法。if (!mCalled) {
thrownew SuperNotCalledException("Fragment " + this
+ " did not call through to super.onViewStateRestored()");
}
}