TabHost empty on rotation Android by using onConfigurationChanged
-
28-06-2021 - |
Question
I have a problem with onConfigurationChanged and TabHost. Because my Activity restart on rotation, I found this very helpful post: Activity restart on rotation Android
I sort gui elements out to the function InitialGui()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InitialGui();
}
Override onConfigurationChanged and call InitialGui()
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
InitialGui();
}
Inside AndroidManifest
<activity
android:label="@string/app_name"
android:name=".MyAndroidAppActivity"
android:theme="@android:style/Theme.NoTitleBar"
android:configChanges="keyboardHidden|orientation"
>
For simplicity I create a new project based on http://www.mkyong.com/android/android-tablayout-example/ with only mentioned changes. This is btw the InitialGui function
public void InitialGui()
{
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost.setup();
// Android tab
Intent intentAndroid = new Intent().setClass(this, AndroidActivity.class);
TabSpec tabSpecAndroid = tabHost
.newTabSpec("Android")
.setIndicator("Android")
.setContent(intentAndroid);
// Apple tab
Intent intentApple = new Intent().setClass(this, AppleActivity.class);
TabSpec tabSpecApple = tabHost
.newTabSpec("Apple")
.setIndicator("Apple")
.setContent(intentApple);
// Windows tab
Intent intentWindows = new Intent().setClass(this, WindowsActivity.class);
TabSpec tabSpecWindows = tabHost
.newTabSpec("Windows")
.setIndicator("Windows")
.setContent(intentWindows);
// Blackberry tab
Intent intentBerry = new Intent().setClass(this, BlackBerryActivity.class);
TabSpec tabSpecBerry = tabHost
.newTabSpec("Berry")
.setIndicator("Berry")
.setContent(intentBerry);
// add all tabs
tabHost.addTab(tabSpecAndroid);
tabHost.addTab(tabSpecApple);
tabHost.addTab(tabSpecWindows);
tabHost.addTab(tabSpecBerry);
//set Windows tab as default (zero based)
tabHost.setCurrentTab(2);
}
My Problem are the empty TabHosts after rotation, doesnt matter witch Tab is clicked nothing is displayed. Any hint? Thanks
Solution
I thought to complex, there is no need to setContentView(R.layout.myLayout); or something else. Simply prevent a call of onCreate method by override onConfigurationChanged.
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
}
this works for me.