Tab change on screen rotation [Android]

不羁岁月 提交于 2019-12-21 06:24:09

问题


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...


回答1:


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.




回答2:


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"));
}



回答3:


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.



来源:https://stackoverflow.com/questions/5675982/tab-change-on-screen-rotation-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!