Handling multiple tabs during landscape and portrait in android

徘徊边缘 提交于 2019-12-10 09:47:07

问题


I have specified different layouts for landscape and portrait using layout and layout-land, my application have multiple tabs. Each time when changing from portrait to landscape or landscape to portrait screen changes to 1st tab even selected tab is different one. How can we solve this problem.


回答1:


You can use onRetainNonConfigurationInstance() to solve this issue.

public void onCreate(Bundle savedInstanceState)
{
   ....
   lastTab = (Integer) getLastNonConfigurationInstance();
   .....
   if(lastTab != null)
   {
      tabs.setCurrentTab(lastTab);
   }
}

public Object onRetainNonConfigurationInstance() 
{
   return tabs.getCurrentTab();
}



回答2:


Rotating the device will, by default, destroy and recreate your Activity. You need to save the state of your selected tab, and restore it when the new Activity is launched.

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    // onCreate implementation goes here

    if(savedInstanceState != null) {
        int selectedTabIndex = savedInstanceState.getInt("selectedTabIndex");
        getActionBar().setSelectedNavigationItem(selectedTabIndex);
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);
    outState.putInt("selectedTabIndex", getActionBar().getSelectedNavigationIndex());
}



回答3:


when you change the orientation it will reload the Activity. That is why its giving 1 st tab.Use in your manifest file android:configChanges="keyboardHidden|orientation" if it will not work fine then go for @Override public void onSaveInstanceState(Bundle savedInstanceState) {}



来源:https://stackoverflow.com/questions/14599050/handling-multiple-tabs-during-landscape-and-portrait-in-android

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