Fragment为什么一定要有无参构造器

        之前听说自定义的Fragment一定要有无参构造器,也就是你在自己定义的Fragment中要么不要声明构造器(默认就是无参构造器),要么你声明了一个有参数构造器的同时一定不要忘记还必须声明一个无参构造器,之前其实只知道这个结论,但是知其然不知其所以然。

        究竟Fragment为什么一定要有无参构造器呢?

        直到生产上真的遇到了如下的崩溃与对应的关键报错信息

Unable to instantiate fragment xxxxxxxx: could not find Fragment constructor

        才去源码中好好学习了一把,弄清楚了缘由。

        去Fragment源码中搜索could not find Fragment constructor,可以找到这样的异常

throw new InstantiationException("Unable to instantiate fragment " + fname
                    + ": could not find Fragment constructor", e);

        该异常是在instantiate()方法中catch到并throw出去的,那我们不妨看看这个instantiate()方法。

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
                            + " that is not a Fragment", new ClassCastException());
                }
                sClassMap.put(fname, clazz);
            }
            Fragment f = (Fragment) clazz.getConstructor().newInstance();
            if (args != null) {
                args.setClassLoader(f.getClass().getClassLoader());
                f.setArguments(args);
            }
            return f;
        } catch (ClassNotFoundException 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 (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);
        }
    }

        可以在方法实现中很容易看到Fragment实例化的时候是调用了反射来实例化的,且反射的构造器是无参构造器!!!

        可以在方法实现中很容易看到Fragment实例化的时候是调用了反射来实例化的,且反射的构造器是无参构造器!!!

        可以在方法实现中很容易看到Fragment实例化的时候是调用了反射来实例化的,且反射的构造器是无参构造器!!!

        重要的事情说三遍!!!

        感觉是某种情况下对Fragment实例化的时候就必须反射无参构造器。

        但是正常流程调试Fragment的时候调用有参构造器怎么就不崩溃呢。而且有条件看生产数据的话你会发现这个页面可能访问量比较大,但是该崩溃并不多啊。会不会是个偶现的崩溃呢?其实不然,这是个必现的崩溃,只不过触发崩溃的条件比较特殊。

        这里为了避免大家着急,先给结论。当只有页面被回收且重绘触发调用onRestoreInstanceState()方法的时候才会触发该bug。

        比个简单的例子,比如你在当前Fragment所在页面操作着,突然去系统设置切了一下字体或者黑夜模式。那就一定会触发该bug。

        我们接下来分析为什么。针对该问题无关紧要的代码我都用...代替了。

        先看下Fragment的onCreate()方法。

@CallSuper
    public void onCreate(@Nullable Bundle savedInstanceState) {
        mCalled = true;
        final Context context = getContext();
        final int version = context != null ? context.getApplicationInfo().targetSdkVersion : 0;
        if (version >= Build.VERSION_CODES.N) {
            restoreChildFragmentState(savedInstanceState, true);
            if (mChildFragmentManager != null
                    && !mChildFragmentManager.isStateAtLeast(Fragment.CREATED)) {
                mChildFragmentManager.dispatchCreate();
            }
        }
    }

        当Android版本大与24时,一定走restoreChildFragmentState()方法。我们看下该方法。

void restoreChildFragmentState(@Nullable Bundle savedInstanceState, boolean provideNonConfig) {
        if (savedInstanceState != null) {
            ...
            if (p != null) {
                ...
                mChildFragmentManager.restoreAllState(p, provideNonConfig ? mChildNonConfig : null);
                ...
            }
        }
    }

        看到了吧,只有savedInstanceState不为空的时候才会执行if里面的语句。这个savedInstanceState什么时候不为空,什么时候就是这个bug必现的场景!!!

        我们继续关注其中的mChildFragmentManager.restoreAllState()方法。

void restoreAllState(Parcelable state, FragmentManagerNonConfig nonConfig) {
        ...
        
        // Build the full list of active fragments, instantiating them from
        // their saved state.
        mActive = new SparseArray<>(fms.mActive.length);
        for (int i=0; i<fms.mActive.length; i++) {
            FragmentState fs = fms.mActive[i];
            if (fs != null) {
                FragmentManagerNonConfig childNonConfig = null;
                if (childNonConfigs != null && i < childNonConfigs.size()) {
                    childNonConfig = childNonConfigs.get(i);
                }
                Fragment f = fs.instantiate(mHost, mContainer, mParent, childNonConfig);
                ...
            }
        }
        
        ...
    }

        这个方法实在是太长了。关键就是for循环中的

Fragment f = fs.instantiate(mHost, mContainer, mParent, childNonConfig);

        再进去看最终就会走到下面的方法中

public Fragment instantiate(FragmentHostCallback host, FragmentContainer container,
            Fragment parent, FragmentManagerNonConfig childNonConfig) {
        if (mInstance == null) {
            ...

            if (container != null) {
                mInstance = container.instantiate(context, mClassName, mArguments);
            } else {
                mInstance = Fragment.instantiate(context, mClassName, mArguments);
            }

            ...
        }
        ...
        return mInstance;
    }

        最关键的就是里层的那一组if else。再往里走最终都会殊途同归到文章最上方的instantiate()方法中,也就是都会反射调用无参构造器来实例化Fragment。

        因此分析了半天,最终结论就是。

        当你的Fragment缺乏无参构造器的时候,正常情况下你通过实例化有参构造器创建并使用Fragment是没毛病的。但是一旦某些情况页面重绘触发到onRestoreInstanceState()的时候,在重建Fragment的过程中,Google会反射调用无参构造器来实例化Fragment对象。那么如果你的Fragment缺少了无参构造器,那就会报:

        could not find Fragment constructor

        至此,分析完毕!!!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值