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.
Fix the screen orientation (landscape or portrait) in
AndroidManifest.xml
android:screenOrientation="portrait"
orandroid:screenOrientation="landscape"
for this your
onResume()
method is not called.You can lock to the current orientation of screen using this code...
People are saying that you should use
But the best and most professional way to handle rotation in Android is to use the Loader class. It's not a famous class(I don't know why), but it is way better than the AsyncTask. For more information, you can read the Android tutorials found in Udacity's Android courses.
Of course, as another way, you could store the values or the views with onSaveInstanceState and read them with onRestoreInstanceState. It's up to you really.
After a while of trial and error, I found a solution which fits my needs in the most situations. Here is the Code:
Manifest configuration:
MainActivity:
And sample Fragment:
Can be found on github.
What you describe is the default behavior. You have to detect and handle these events yourself by adding:
to your manifest and then the changes that you want to handle. So for orientation, you would use:
and for the keyboard being opened or closed you would use:
If you want to handle both you can just separate them with the pipe command like:
This will trigger the onConfigurationChanged method in whatever Activity you call. If you override the method you can pass in the new values.
Hope this helps.
Use
orientation
listener to perform different tasks on different orientation.