There are some similar answers, but not to this situation.
My situation is simple.
I have an Activity with two different layouts, one in Portrait,
I finally come up with a solution to prevent unwanted Fragment re-creating upon the Activity re-creates. It is like what i mentioned in the question:
The only neat way i found is doing
getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentById(R.id.FragmentContainer)).commit();
inonSaveInstanceState()
. But it will raise another problems...
... with some improvements.
In onSaveInstanceState()
:
@Override
protected void onSaveInstanceState(Bundle outState) {
if (isPortrait2Landscape()) {
remove_fragments();
}
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 we 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.
*Be sure we remove_fragments()
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.