在方向改变保存选项卡状态选项卡、方向、状态

2023-09-05 03:29:35 作者:何必千娇百媚℅▼

我有2个选项卡,例如TAB1和放大器;这是显示在屏幕上TAB2。让选项卡显示在纵向方向。

I have 2 tabs , for example Tab1 & Tab2 which is displayed on the screen. Let the tabs be displayed on the PORTRAIT orientation.

TAB1显示活动1&放大器; TAB2显示活性2。

Tab1 displays Activity1 & Tab2 displays Activity2.

目前,所选择的选项卡状态是TAB2。现在,我改变方向为纵向到横向。在改变方向为横向模式,而不是显示TAB2,目前TAB1显示。

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.

为了执行保存选项卡状态的目的,我写了下面的code:

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

}

我想知道的,是我的做法正确与否和放大器;无论是上述code是节约了改变方向的标签状态的正确方法。

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.

推荐答案

这是不是最好的方式。您应该使用onRetainNonConfigurationInstance()和getLastNonConfigurationInstance(),以保持配置的变化之间的状态。这些方法是专门为在配置修改节能状态。

That's not the best way. You should use onRetainNonConfigurationInstance() and getLastNonConfigurationInstance() to retain the state between config changes. Those methods are specifically for saving state during config changes.

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

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