plowman
plowman

Reputation: 13585

Android App Losing State When Switching Tabs And Orientation

The problem: I have a tabbed android app and I'm losing the content in TabOne whenever I follow these (admittedly strange) steps:

  1. Change to another tab.
  2. Switch orientation to landscape.
  3. Switch orientation back to portrait.
  4. Change back to TabOne.

Android App Description: I have a pretty bare-bones android app with three tabs that were built using google's TabLayout tutorial, we'll call them TabOne, TabTwo, and TabThree. Only TabOne has any content: a simple EditText view and Button that lets you add text to the body of TabOne. This is rigged up using a custom ArrayAdapter, which may have something to do with the strange behavior.

Note that this does not occur if I change orientation while remaining on TabOne. This is because I have implemented OnSaveInstanceState() and OnRestoreInstanceState() to save my list of data in my TabOneActivity class.

Upvotes: 2

Views: 1970

Answers (2)

user1734624
user1734624

Reputation: 143

I had the same problem - the solution I found was to create a 'Dummy' tab and activity for the first tab in the TabLayout onCreate, then in onResume of the Tab Layout Activity, hide the 'Dummy' tab and select the 2nd tab programmatically. Not nice, but works as saves state of 2nd tab (i.e. 1st visible tab).

@Override

protected void onResume() {

    super.onResume();

    if (getTabHost() != null && getTabHost().getTabWidget()!= null) {

        getTabHost().getTabWidget().getChildAt(0).setVisibility(View.GONE);

        if (getTabHost().getCurrentTab() == 0) {

            getTabHost().setCurrentTab(1);

        }

    }

}

Upvotes: 4

dave.c
dave.c

Reputation: 10908

You also need to restore your activity state in onCreate, as well as in OnRestoreInstanceState.

I should point out though that this technique is only for transient data, not for long term data storage. For that you should be saving the data to a database or to SharedPreferences in onPause, and then retrieving the data in onResume.

Upvotes: 1

Related Questions