I have 2 tabs , for example Tab1 & Tab2 which is displayed on the screen. Let the tabs be displayed on the PORTRAIT orientation.
Tab1 displays Activity1 & Tab2 displays Activity2.
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.
My code:
public class TabBarExample extends 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();
}
}
Check this answer.
You have to play with SaveInstanceState
and RestoreInstanceState
.
See this Example.