美文网首页
为什么fragment不能用构造函数传参数

为什么fragment不能用构造函数传参数

作者: 卡路fly | 来源:发表于2020-05-30 11:41 被阅读0次
  1. fragment的构造函数是空的
// 构造方法
public Fragment() {
}
  1. instantiate方法中创建了fragment对象
public static Fragment instantiate(Context context, String fname){
        return instantiate(context, fname, null);
}
  1. 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);           

相关文章

网友评论

      本文标题:为什么fragment不能用构造函数传参数

      本文链接:https://www.haomeiwen.com/subject/peuczhtx.html