Preservation of the state of the tab during orientation changes

I have 2 tabs, for example Tab1 and Tab2, which are displayed on the screen. Let the tabs appear in the PORTRAIT orientation.

Tab1 displays Activity1 and Tab2 displays Activity2.

The currently selected tab state is Tab2. Now I am changing the orientation for the PORTRAIT in the LANDSCAPE. When changing the orientation in LANDSCAPE mode, the Tab1 tab is displayed instead of displaying Tab2.

Basically, I want to keep the Tab state when changing orientation.

To complete the task of saving the state of a tab, I write the following code:

protected void onPause() { super.onPause(); saveCurrentTabState(getSelectedTab()); } private void saveCurrentTabState(int value) { PreferenceManager.getDefaultSharedPreferences(this).edit().putInt( "tabState", value).commit(); } @Override protected void onResume() { super.onResume(); setCurrentTab(PreferenceManager.getDefaultSharedPreferences(this) .getInt("tabState", 0)); } 

I wanted to know whether my approach is correct or not, and whether the above code matches the correct way to maintain the tab state when changing orientation.

+8
android
source share
2 answers

This is not the best way. You must use onRetainNonConfigurationInstance () and getLastNonConfigurationInstance () to maintain state between configuration changes. These methods are specifically designed to maintain state during configuration changes.

 public Object onRetainNonConfigurationInstance() { return mTabHost.getCurrentTab(); } public void onCreate() { ... Integer lastTab = (Integer) getLastNonConfigurationInstance(); if(lastTab != null) { mTabHost.setCurrentTab(lastTab); } ... } 
+2
source share

This is not how it should be done ... use instead:

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

Then using the onCreate method:

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

Robby's solution will also work and uses the onRetainNonConfigurationInstance method. I really like and prefer this method over onSaveInstanceState , as it allows you to save a complex object that represents the state of the application, not just parceables inside the Bundle .

So when to use one of the other? It depends on the data needed to save / restore the state of the application. For simple things, such as maintaining the state of a tab, this is almost the same.

+18
source share

All Articles