Well, i guess this simple way can serve what i want to:
Not to add <activity android:configChanges="orientation" >
. Means NO NEED OVERRIDE onConfigurationChanged()
.
In onSaveInstanceState()
:
@Override
protected void onSaveInstanceState(Bundle outState) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
do_something();
}
super.onSaveInstanceState(outState);
}
* Be sure you do_something()
before super.onSaveInstanceState()
.
(Because in my case, i remove the Fragments from the Layout, and from the Activity. If it is after super.onSaveInstanceState()
, the Layout will already be saved into the Bundle. Then the Fragments will also be re-created after the Activity re-creates. ###)
### I have proved this phenomenon. But the reason of What to determine a Fragment restore upon Activity re-create? is just by my guess. If you have any ideas about it, please answer my another question. Thanks!
Well, further improvement on the method above, which fixes the problem raised in the first comment: (still simple)
@Override
protected void onSaveInstanceState(Bundle outState) {
if (isPortrait2Landscape()) {
do_something();
}
super.onSaveInstanceState(outState);
}
private boolean isPortrait2Landscape() {
return isDevicePortrait() && (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE);
}
and the isDevicePortrait()
would be like:
private boolean isDevicePortrait() {
return (findViewById(R.id.A_View_Only_In_Portrait) != null);
}
* Notice that we cannot use getResources().getConfiguration().orientation
to determine if the device is currently literally Portrait. It is because the Resources
object is changed RIGHT AFTER the screen rotates - EVEN BEFORE onSaveInstanceState()
is called!!
If you do not want to use findViewById()
to test orientation (for any reasons, and it's not so neat afterall), keep a global variable private int current_orientation;
and initialise it by current_orientation = getResources().getConfiguration().orientation;
in onCreate()
. This seems neater. But we should be aware not to change it anywhere during the Activity lifecycle.