Fragment没有无参构造器引发的惨案

2021-04-27  本文已影响0人  waiwaaa

bugly上有一个InstantiationException的异常

java.lang.InstantiationException
java.lang.Class<com.xx.factory.fragment.xxx> has no zero argument constructor
com.xx.factory.ui.theme.base.ThemeBaseFragmentActivity.void onCreate(android.os.Bundle)(TbsSdkJava:1)
java.lang.RuntimeException:Unable to start activity ComponentInfo{com.xx.yy/com.xx.factory.ModxxActivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.xx.factory.fragment.ModxxFragment: make sure class name exists, is public, and has an empty constructor that is public
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3543)

大概意思是没有提供Fragment的无参构造方法,翻看对应的ModxxActivity,调用的都是有参的构造方法,怎么会出现这个错误呢?

从Fragment的默认构造器注释我们可以看到如下描述

/**
     * Default constructor.  <strong>Every</strong> 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 {@link #setArguments}
     * and later retrieved by the Fragment with {@link #getArguments}.
     * 
     * <p>Applications should generally not implement a constructor. Prefer
     * {@link #onAttach(Context)} instead. It is the first place application code can run where
     * the fragment is ready to be used - the point where the fragment is actually associated with
     * its context. Some applications may also want to implement {@link #onInflate} to retrieve
     * attributes from a layout resource, although note this happens when the fragment is attached.
     */
    public Fragment() {
    }

每一个Fragment必须有一个无参的构造函数,Activity恢复状态时fragment可以实例化。
建议fragment的子类不要有其他的有参构造函数,因为当fragment重新实例化时不会调用这些有参构造函数,参数用setArguments来传递

上一篇下一篇

猜你喜欢

热点阅读