Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save the Tab state during orientation change

Tags:

android

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 & Tab2 displays Activity2.

Currently , the selected tab state is Tab2 . Now , I change the orientation for PORTRAIT to LANDSCAPE . On changing the orientation to LANDSCAPE mode , instead of displaying Tab2 , currently Tab1 is displayed.

Basically , I want to save the Tab state when there is orientation change.

In order to perform the objective of saving the tab state , I am writing 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 , is my approach correct or not & whether the above code is a proper way of saving the tab state on changing the orientation.

like image 831
chiranjib Avatar asked Mar 15 '11 20:03

chiranjib


1 Answers

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.

like image 76
Cristian Avatar answered Oct 03 '22 17:10

Cristian