美文网首页
Fragment没有无参构造器引发的惨案

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

作者: waiwaaa | 来源:发表于2021-04-27 10:21 被阅读0次

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来传递

相关文章

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

    bugly上有一个InstantiationException的异常 大概意思是没有提供Fragment的无参构造...

  • Fragment 复习总结

    主要内容: 1、Fragment 的生命周期 2、Fragment 的管理 3、Fragment 的空参构造方法 ...

  • 报错总结

    在报错信息中看到 ()初始化错误基本就是 没有无参构造器

  • Fragment

    生命周期 使用Fragment时,必要构建一个无参构造函数,系统会默认带。但一但写有参构造函数,就必要构建无参构造...

  • java_7_构造器

    一、默认构造器 二、无参构造器 三、有参构造器 如果没有自定义构造器,则会默认自动生成一个无参构造器如果有自定义构...

  • 20170830-NamedParameterJdbcTempl

    说明:该对象可以使用具名参数,其没有无参的构造器,所以必须为其构造器指定参数 讲解 在经典的 JDBC 用法中, ...

  • 什么情况下Activity会被杀掉呢?

    首先一个报错来作为开篇: 这个报错原因就是Fragment如果重载了有参的构造方法,没有实现默认无参构造方法。Ac...

  • Java面向对象

    1、子类实例化时会默认调用父类无参构造函数,如果父类没有无参构造函数,则需要子类构造函数显示调用父类有参构造函数 ...

  • java编程思想5-初始化与清理

    1 构造器 不接受任何参数的构造器叫做默认构造器,如果没有编写构造器,则会自动创建无参构造器。如果有构造器,则不会...

  • python-迭代器

    迭代器 1、构造方法 init() 无参构造和有参构造 class Foo(): def __init__(s...

网友评论

      本文标题:Fragment没有无参构造器引发的惨案

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