为什么fragment不能用构造函数传参数
2020-05-30 本文已影响0人
卡路fly
- fragment的构造函数是空的
// 构造方法
public Fragment() {
}
- instantiate方法中创建了fragment对象
public static Fragment instantiate(Context context, String fname){
return instantiate(context, fname, null);
}
- instantiate
Class<?> clazz = sClassMap.get(fname);
if (clazz == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = context.getClassLoader().loadClass(fname);
if (!Fragment.class.isAssignableFrom(clazz)) {
throw new InstantiationException("Trying to instantiate a class " + fname
+ " that is not a Fragment", new ClassCastException());
}
sClassMap.put(fname, clazz);
}
Fragment f = (Fragment)clazz.newInstance();
if (args != null) {
args.setClassLoader(f.getClass().getClassLoader());
f.mArguments = args;
}
return f;
Fragment是用反射的方式创建的,而且有mArguments来控制参数。因此要用特定的方式来传递参数:
// 用bundle对象来传递参数
Bundle bundle = new Bundle();
bundle.putSerializable("entity", entity);
fragment.setArguments(bundle);