如何在android中定位期间保存选项卡状态

时间:2012-08-02 06:57:38

标签: android-tabhost

我有两个标签,例如Tab1& Tab2显示在屏幕上。让标签显示在肖像方向上。

Tab1显示Activity1& Tab2显示Activity2。

目前,选定的选项卡状态为Tab2。现在,我将PORTRAIT的方向更改为LANDSCAPE。在将方向更改为LANDSCAPE模式时,不显示Tab2,而是显示当前的Tab1。

我的代码:

public class TabBarExample扩展TabActivity {

TabHost tabHost;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab);

    /* TabHost will have Tabs */
    tabHost= (TabHost)findViewById(android.R.id.tabhost);

    TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
    TabSpec secondTabSpec = tabHost.newTabSpec("tid1");


    firstTabSpec.setIndicator("First Tab Name").setContent(new Intent(this,FirstTab.class));
    secondTabSpec.setIndicator("Second Tab Name").setContent(new Intent(this,SecondTab.class));


    tabHost.addTab(firstTabSpec);
    tabHost.addTab(secondTabSpec);



    tabHost.getTabWidget().getChildAt(0).getLayoutParams().height =40;
    tabHost.getTabWidget().getChildAt(1).getLayoutParams().height =40;

    for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)  
    {  
        tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#8A4117"));  
    }  

    Integer lastTab = (Integer) getLastNonConfigurationInstance();
    if(lastTab != null) {
       tabHost.setCurrentTab(lastTab);
    } 
    tabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.parseColor("#C35817"));  
} 
public void onTabChanged(String tabId) {  
    // TODO Auto-generated method stub  
    for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)  
    {  
        tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#8A4117"));  
    }  

    tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#C35817"));  


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

}

1 个答案:

答案 0 :(得分:3)

检查this answer

您必须使用SaveInstaceStateRestoreInstanceState

请参阅此Example

To know more Read this