【问题标题】:Is the Bundle passed on onCreate to Activity and Child Fragment different?在 onCreate 上传递给 Activity 和 Child Fragment 的 Bundle 是否不同?
【发布时间】:2016-08-03 10:27:15
【问题描述】:

Bundle 的私有副本是否传递给Fragment 和父Activity

我尝试将键值对保存在FragmentonSaveInstanceState 中,并尝试在Activity 的onCreate 中检索它。那里不存在。

但两者之间似乎也有联系。 当我将null 传递给Activitysuper.onCreate 时,传递给FragmentBundleonCreate 也是null

【问题讨论】:

  • 它们完全不同。
  • @xAqweRx 然后当我将null 传递给Activitysuper.onCreate 时,传递给FragmentBundle 也是null。为什么会这样?
  • 在此处粘贴您的代码。
  • @xAqweRx 是公司代码。我不能在这里分享。请告诉我,哪个部分需要更多澄清,我会澄清。

标签: android android-fragments android-activity activity-lifecycle fragment-lifecycle


【解决方案1】:

Bundle 发送到onCreate,因为ActivityFragment 完全不同。如果您将null 发送到super.onCreate -> 活动将从头开始重新创建所有fragments。所以你的Fragment 也会收到null ->。因为这是新的fragment


这是FragmentActivity的一部分代码:

/**
 * Perform initialization of all fragments and loaders.
 */
@SuppressWarnings("deprecation")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    mFragments.attachHost(null /*parent*/);

    super.onCreate(savedInstanceState);

    NonConfigurationInstances nc =
            (NonConfigurationInstances) getLastNonConfigurationInstance();
    if (nc != null) {
        mFragments.restoreLoaderNonConfig(nc.loaders);
    }
    if (savedInstanceState != null) {
        Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
        mFragments.restoreAllState(p, nc != null ? nc.fragments : null);

        // Check if there are any pending onActivityResult calls to descendent Fragments.
        if (savedInstanceState.containsKey(NEXT_CANDIDATE_REQUEST_INDEX_TAG)) {
            mNextCandidateRequestIndex =
                    savedInstanceState.getInt(NEXT_CANDIDATE_REQUEST_INDEX_TAG);
            int[] requestCodes = savedInstanceState.getIntArray(ALLOCATED_REQUEST_INDICIES_TAG);
            String[] fragmentWhos = savedInstanceState.getStringArray(REQUEST_FRAGMENT_WHO_TAG);
            if (requestCodes == null || fragmentWhos == null ||
                        requestCodes.length != fragmentWhos.length) {
                Log.w(TAG, "Invalid requestCode mapping in savedInstanceState.");
            } else {
                mPendingFragmentActivityResults = new SparseArrayCompat<>(requestCodes.length);
                for (int i = 0; i < requestCodes.length; i++) {
                    mPendingFragmentActivityResults.put(requestCodes[i], fragmentWhos[i]);
                }
            }
        }
    }

    if (mPendingFragmentActivityResults == null) {
        mPendingFragmentActivityResults = new SparseArrayCompat<>();
        mNextCandidateRequestIndex = 0;
    }

    mFragments.dispatchCreate();
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
相关资源
最近更新 更多