Fragment f = clazz.getConstructor().newInstance();
public static Fragment instantiate(@NonNull Context context, @NonNull String fname,
@Nullable Bundle args) {
try {
Class<? extends Fragment> clazz = FragmentFactory.loadFragmentClass(
context.getClassLoader(), fname);
Fragment f = clazz.getConstructor().newInstance();
if (args != null) {
args.setClassLoader(f.getClass().getClassLoader());
f.setArguments(args);
}
return f;
} catch (java.lang.InstantiationException e) {
throw new 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) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": make sure class name exists, is public, and has an"
+ " empty constructor that is public", e);
} catch (NoSuchMethodException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": could not find Fragment constructor", e);
} catch (InvocationTargetException e) {
throw new InstantiationException("Unable to instantiate fragment " + fname
+ ": calling Fragment constructor caused an exception", e);
}
}
主要看一下注释说明,如果你想要的使用非默认的构造函数,需要自己实现一个FragmentFactory去初始化,然后强烈推荐使用setArguments和getArguments存取参数。看了一下报错的类,可以基本确定是使用了带参数的构造函数
然后看一下报错的位置,在Fragment里搜索could not find Fragment constructor
但是对应的类没有空的构造函数,所以抛出了这个异常。然后看一下初始的地方,是FragmentActivity在onCreate中调用的mFragments.restoreSaveState(p);
结论:
Fragment必须有一个无参public的构造函数,否则在数据恢复的时候,会报crash
ps:手动测试发现私有的构造函数无法通过该Constructor.newInstance方法调用