实施 onSavedInstanceState 会停止 FragmentStatePagerAdapter 的工作

Implementing onSavedInstanceState stops FragmentStatePagerAdapter working

在我的 activity 中,我发现我需要在选项卡式视图中存储其中一个选项卡的状态。这是搜索栏的结果,我需要一个 Activity 来接收和存储数据。

虽然我的应用程序在手头上工作,但当我在 Activity

中实施时
public void onSaveInstanceState( Bundle outState ){
    ArrayList<SearchData.SearchDataSerial> sdSerial = new ArrayList<SearchData.SearchDataSerial>();
    int i;
    for( i = 0; i < mSearchData.size() ; i++ ){
        SearchData item = mSearchData.get(i);
        SearchData.SearchDataSerial elem = new SearchData.SearchDataSerial( item );
        sdSerial.add( elem );
    }
    outState.putParcelableArrayList( "searchterms", sdSerial );


    Log.d( TAG, "OnSaveInstanceState" );
}

它破坏了选项卡中所有其他片段的持久性。

此外,如果在 activity 的 onCreate 中,如果我必须将我的代码更改为此以保持页面加载。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /* ... not relevant */
    // if( savedInstanceState == null ) { /* had to comment out this line */
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        SlidingTabsBasicFragment fragment = new SlidingTabsBasicFragment();
        transaction.replace(R.id.tabbed_layout_main, fragment);
        transaction.commit();
    //} /* had to comment out this line */
    if (savedInstanceState != null) {
        loadSavedData( savedInstanceState );
    }

    setupActionBar();
}

正如 docs 所说:

Caution: You must always call the superclass implementation of onSaveInstanceState() so the default implementation can save the state of the view hierarchy.

所以正确的代码应该是这样的...

@Override
public void onSaveInstanceState( Bundle outState ){
    super.onSaveInstanceState( outState ); /* Needs to be here for framework to work */
    ArrayList<SearchData.SearchDataSerial> sdSerial = new ArrayList<SearchData.SearchDataSerial>();
    int i;
    for( i = 0; i < mSearchData.size() ; i++ ){
        SearchData item = mSearchData.get(i);
        SearchData.SearchDataSerial elem = new SearchData.SearchDataSerial( item );
        sdSerial.add( elem );
    }
    outState.putParcelableArrayList( "searchterms", sdSerial );


Log.d( TAG, "OnSaveInstanceState" );
}