Android Fragment getActivity返回null解决

在Android开发中,在使用Fragment时,不管是用support v7中的ActionBarActivity,还是在SDk version 21出现的AppCompatActivity,都是继承自FragmentActivity,在应用被切换到后台的时候,Activity可能被回收,在回收之前都会执行FragmentActivity中的onSaveInstanceState方法保存所有Fragment的状态,如下所示。下面是FragmentActivity的部分源码:
/**
     * Save all appropriate fragment state.
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Parcelable p = mFragments.saveAllState();
        if (p != null) {
            outState.putParcelable(FRAGMENTS_TAG, p);
        }
    }

,重新启动该activity时系统会恢复之前被回收的Activity,这个时候FragmentActivity在onCreate里面也会做Fragment的恢复。

/**
     * 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);
        }
        mFragments.dispatchCreate();
    }


 
  
 
  

这里我的解决方法是在恢复Fragment之前把保存Bundle里面的数据给清除。赶在Activity恢复其之前所绑定的Fragment之前清除所有存储在savedInstanceState中的信息。方法如下:

if (savedInstanceState != null) {
            savedInstanceState.putParcelable("android:support:fragments", null);
        }
super.onCreate(savedInstanceState);




你可能感兴趣的:(Android Fragment getActivity返回null解决)