代码之家  ›  专栏  ›  技术社区  ›  Mir-Ismaili

为什么片段类应该是公共的?

  •  3
  • Mir-Ismaili  · 技术社区  · 6 年前

    我找到了一些线索来解释为什么 Fragment 类应该是 static (不是) 非静态内部 喜欢 this . 但无法理解此错误消息的原因:

    这个片段类应该是公共的(…)


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

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

    碎片应该只用于 MainActivity .


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

    从片段文档:

    每个片段都必须有一个空的构造函数,以便在恢复其活动状态时对其进行实例化。强烈建议子类不具有其他带参数的构造函数,因为在重新实例化片段时不会调用这些构造函数;相反,调用方可以使用setArguments(bundle)提供参数,稍后使用getArguments()由片段检索参数。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Pankaj Kumar    6 年前


    Fragment.Fragment()

    Default constructor :

    empty constructor setArguments(Bundle) Fragment getArguments()


    Activity.java 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();
        .....
    }
    
        2
  •  0
  •   Super User User    6 年前