Fragment沒有無參構造器引發的慘案

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來傳遞

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章