Hi I have Android APP with 4 tabs (let's say tab1, tab2, tab3, tab4). When activity starts default tab is tab1. Than I switch to any other tab (tab2, 3 or 4) and change screen orientation and it always resets to default tab (tab1).
I tried with the following code:
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
createView();
}
And inside createView() I have:
private void createView()
{
... // Tabs are created before
tabHost.getTabWidget().setCurrentTab(CurrentTab);
}
CurentTab
is private int and is default set to 0, but it is set on TabChange:
public void onTabChanged(String tabId) {
... some code
CurrentTab = tabHost.getCurrentTab();
}
I am stacked here... is there any other way to solve this problem?
Shortly: I want that Tab isn't changed to default on screen rotation...
The problem is, that on a configuration change like the rotation of the screen the current activity gets destroyed and recreated. In case of a tab activity this includes the tab activity itself and also the activities of each tab.
So when it got recreated it simply shows the first tab as it has no other information.
To fix this you can override onRetainNonConfigurationInstance()
of you tab activity and return the current selected tab. In the on onCreate of the tab activity you then call getLastNonConfigurationInstance()
which returns the object you returned in onRetainNonConfigurationInstance(). If the object is null, you know that there was no orientation change so you simply select the first tab, if it isn't null then there was a screen rotation and you can use the returned value to decide which tab was selected before and set it again.
so you have to implement this by overriding onSaveInstanceState(Bundle) in your activity
coz when screen rotate activity is recreated
EDIT:
protected void onSaveInstanceState (Bundle outState){
outState.putInt("LastTab", tabHost.getCurrentTab());
}
protected void onCreate (Bundle savedInstanceState){
super.onCreate (savedInstanceState);
//...tabs creation
// u need to provide some code to check if "LastTab" exists in savedState
tabHost.getTabWidget().setCurrentTab(savedInstanceState.getInt("LastTab"));
}
To expand on Flo's answer - Activity method onRetainNonConfigurationInstance()
has been deprecated since Honeycomb 3.2 (API 13):
This method was deprecated in API level 13.
Use the new Fragment
API setRetainInstance(boolean)
instead; this is also available on older platforms through the Android compatibility package.
Makes usage a little easier, IMHO.