I need to apply different layouts for portrait and landscape orientations of my activity. Besides, I need to show alert if orientation is portrait.
I have specified android:configChanges="orientation|keyboardHidden"
in AndroidManifest. I also override onConfigurationChanged method like this:
@Override
public void onConfigurationChanged(Configuration newConfig)
{
Log.d("tag", "config changed");
super.onConfigurationChanged(newConfig);
int orientation = newConfig.orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT)
Log.d("tag", "Portrait");
else if (orientation == Configuration.ORIENTATION_LANDSCAPE)
Log.d("tag", "Landscape");
else
Log.w("tag", "other: " + orientation);
....
}
While rotating from landscape to portrait log looks like:
config changed
Portrait
But while changing from portrait to landscape it looks like
config changed
Portrait
config changed
Landscape
Why onConfigurationChanged is called twice? How can I avoid it?
See my answer to another question here: https://stackoverflow.com/a/3252547/338479
In short, handling configuration changes correctly is hard to do. It's best to implement onRetainNonConfigurationInstance() which is called just before your application is about to be stopped and restarted due to a configuration change. Use this method to save anything you want ('this' is a good choice) and then let the system tear down your app.
When your app gets restarted with the new configuration, use getLastNonConfigurationInstance() to retrieve the state you just saved, and use it to continue your application without all that mucking about with bundles and shared preferences.