为什么片段 class 应该是 public?

Why fragment class should be public?

我发现一些线程可以解释为什么 Fragment class 应该是 static(而不是 非静态内部 ),例如 this。但无法理解此错误消息的原因:

This fragment class should be public (...)


我使用 Android Studio 3.1.2,这是我的代码的一部分:

public class MainActivity extends android.support.v7.app.AppCompatActivity {
    // ...
}

class DefaultFragment extends android.support.v4.app.Fragment {
    // ...
}

该片段应该只用于 MainActivity


编辑:IDE 消息中还有一些其他信息。但是关于构造函数:

From the Fragment documentation:

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().

在方向改变时,Activity 重新创建并且框架在片段上创建新实例(并恢复以前的状态)。 所以这里创建Fragment的实例,框架要求提供public构造函数。


来自 Fragment.Fragment()

的文档

Default constructor :

每个片段都必须有一个 empty constructor,因此它可以在恢复其 activity 的状态时被实例化。强烈建议子类不要有其他带参数的构造函数,因为这些构造函数在片段重新实例化时不会被调用;相反,调用者可以使用 setArguments(Bundle) 提供参数,然后由 Fragment 使用 getArguments().

检索

下面是代码形式Activity.java class and you can analysis further in looking more codes of FragmentManager.dispatchMoveToState()

@MainThread
@CallSuper
protected void onCreate(@Nullable Bundle savedInstanceState) {
    ........
    if (savedInstanceState != null) {
        mAutoFillResetNeeded = savedInstanceState.getBoolean(AUTOFILL_RESET_NEEDED, false);
        mLastAutofillId = savedInstanceState.getInt(LAST_AUTOFILL_ID,
                View.LAST_APP_AUTOFILL_ID);
        if (mAutoFillResetNeeded) {
            getAutofillManager().onCreate(savedInstanceState);
        }
        Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
        mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
                ? mLastNonConfigurationInstances.fragments : null);
    }
    mFragments.dispatchCreate();
    .....
}

这也是因为内部 类 持有对其父级 类 的引用,这可能会泄漏 Activity.

Non static inner classes do hold a reference to their parent classes. The problem with making a Fragment inner class non-static is that you always hold a reference to the Activity. The GarbageCollector cannot collect your Activity. So you can 'leak' the Activity if for example the orientation changes. Because the Fragment might still live and gets inserted in a new Activity.

检查detailed answer和制作片段的尝试