Being frustrated about fragment behavior, I started doing some testing.
I have one activity and 2 fragments. Fragment A is declared inside the xml layout of the activity and Fragment B is added (only if it's not present) in the layout of the activity in activity's onCreate()
method. I've added logging in all of the main lifecycle methods for the activity and the 2 fragments and tested the behavior when switching orientation back and forth. Here are my findings:
Fragment B (the dynamically-added fragment) behaves as expected:
a) after an orientation change, the savedInstanceState
bundle contains what has been previously saved in onSaveInstanceState()
b) if setRetainInstance(true)
, during an orientation change, onDestroy()
is not called and also the subsequent onCreate()
is not called. The fragment's fields are preserved during the orientation change
Fragment A (the fragment defined in the xml layout) doesn't behave as expected:
a) after an orientation change, the savedInstanceState bundle is always null although onSaveInstanceState()
has been properly called
b) if setRetainInstance(true)
, during an orientation change, onDestroy()
is not called as expected BUT, contrary to what is expected, onCreate()
is also called when the fragment is being reattached. And also, the fragment's fields are not preserved.
To sum up, for fragments declared inside xml layouts and using ACL v4, saving state during orientation changes does not work and setRetainInstance(true) does not work.
My question is if someone tested this functionality on Android 3.0+ and can say if fragments work correctly when using fragments from Android SDK.
One workaround to this problem would be to always dynamically create my fragments. Did anyone find a different workaround?