为什么需要一个无参构造函数的Fragment

之前在用Android Lint时发现里面有个选项“Fragment not instantiatable”

这里写图片描述

Every fragment must have an empty constructor, so it can be instantiated when restoring its activity’s state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments().
  Fragment文档中说明,自定义Fragment时强烈建议我们不使用有参构造函数,以便可以再次实例化。这可是Fragment的一大火坑呀,我们在写一个类的时候,通常都是通过有参的构造函数传入需要的参数,Fragment却反其道而行之,相信很多人已经跳进了这个火坑。虽然文档上说了实例化是可能会出现问题,但是并没有具体指出是哪一行代码出错,既然这样,只有自己动手,到源码中去一探究竟。在Fragment的源码中,发现instantiate(Context context, String fname, @Nullable Bundle args)这个方法会抛出找不到非空构造函数的异常:

  public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
      try {
          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
                          + 
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值