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 way I have found to do this is use the
onRestoreInstanceState
and theonSaveInstanceState
events to save something in theBundle
(even if you dont need any variables saved, just put something in there so theBundle
isn't empty). Then, on theonCreate
method, check to see if theBundle
is empty, and if it is, then do the initialization, if not, then do it.Every time when screen is rotated, opened activity is finished and onCreate() is called again.
1 . You can do one thing save the state of activity when screen is rotated so that, You can recover all old stuff when activity's onCreate() is called again. Refer this link
2 . If you want to prevent restarting of the activity just place following lines in your manifest.xml file.
Update for Android 3.2 and higher:
There are several ways to do this:
Save Activity State
You can save the activity state in
onSaveInstanceState
.and then use the
bundle
to restore the state.Handle orientation changes by yourself
Another alternative is to handle the orientation changes by yourself. But this is not considered a good practice.
Add this to your manifest file.
for Android 3.2 and later:
Restrict rotation
You can also confine your activity to portrait or landscape mode to avoid rotation.
Add this to the activity tag in your manifest file:
Or implement this programmatically in your activity:
You may use ViewModel object in your activity.
ViewModel objects are automatically retained during configuration changes so that data they hold is immediately available to the next activity or fragment instance. Read more:
https://developer.android.com/topic/libraries/architecture/viewmodel
you need to use the onSavedInstanceState method to store all the value to its parameter is has that is bundle
and use
to retrive and set the value to view objects it will handles the screen rotations