Save the Tab state during orientation change

前端 未结 2 1501
不思量自难忘°
不思量自难忘° 2020-12-31 16:30

I have 2 tabs , for example Tab1 & Tab2 which is displayed on the screen. Let the tabs be displayed on the PORTRAIT orientation.

Tab1 displays Activity1 & Ta

相关标签:
2条回答
  • 2020-12-31 17:10

    That's not the best way. You should use onRetainNonConfigurationInstance() and getLastNonConfigurationInstance() to retain the state between config changes. Those methods are specifically for saving state during config changes.

    public Object onRetainNonConfigurationInstance() {
        return mTabHost.getCurrentTab();
    }
    
    public void onCreate() {
       ...
       Integer lastTab = (Integer) getLastNonConfigurationInstance();
       if(lastTab != null) {
          mTabHost.setCurrentTab(lastTab);
       }
       ...
    }
    
    0 讨论(0)
  • 2020-12-31 17:21

    That's not the way it should be done... instead use the:

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tabState", getSelectedTab());
    }
    

    Then, on the onCreate method:

    public void onCreate(Bundle state){
         // do the normal onCreate stuff here... then:
         if( state != null ){
             setCurrentTab(state.getInt("tabState"));
         }
    }
    

    The Robby's solution will work too and involves using the onRetainNonConfigurationInstance method. I actually like and prefer that method over onSaveInstanceState since it allows you save a complex object that represents the state of the app, not only parceables inside a Bundle.

    So when to use one of the other? It depends on the data you need to save/restore the state of the app. For simple things like saving the tab state, it's almost the same.

    0 讨论(0)
提交回复
热议问题