In my Android application, when I rotate the device (slide out the keyboard) then my Activity
is restarted (onCreate
is called). Now, this is probably how it's supposed to be, but I do a lot of initial setting up in the onCreate
method, so I need either:
- Put all the initial setting up in another function so it's not all lost on device rotation or
- Make it so
onCreate
is not called again and the layout just adjusts or - Limit the app to just portrait so that
onCreate
is not called.
The
onCreate
method is still called even when you change theorientation
of android. So moving all the heavy functionality to this method is not going to help youNote: I post this answer if someone in the future face the same problem as me. For me the following line wasn't enought:
When I rotated the screen, the method `onConfigurationChanged(Configuration newConfig) did't get called.
Solution: I also had to add "screenSize" even if the problem had to do with the orientation. So in the AndroidManifest.xml - file, add this:
Then implement the method
onConfigurationChanged(Configuration newConfig)
Add this line in manifest :
android:configChanges="orientation|screenSize"
Put this below code in your
Activity
inAndroid Manifest
.This will not restart your activity when you would change orientation.
what I did...
in the manifest, to the activity section, added:
in the code for the activity, implemented:
I just discovered this lore:
For keeping the Activity alive through an orientation change, and handling it through
onConfigurationChanged
, the documentation and the code sample above suggest this in the Manifest file:which has the extra benefit that it always works.
The bonus lore is that omitting the
keyboardHidden
may seem logical, but it causes failures in the emulator (for Android 2.1 at least): specifying onlyorientation
will make the emulator call bothOnCreate
andonConfigurationChanged
sometimes, and onlyOnCreate
other times.I haven't seen the failure on a device, but I have heard about the emulator failing for others. So it's worth documenting.