Loss of variables switching orientations
make sure you implement onSaveInstanceState
and be prepared to restore your activity from a Bundle
in onCreate
and you'll be all set. these will be called during rotation, so you'll have a new activity afterwards, but if you've saved your state and can restore it, nothing to worry about.
This is by design, onCreate
will be called when orientation is changed. If this is not desired, you can set it not to respond to orientation changes in AndroidManifest.xml
, thus your activity will not be recreated, setting android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden"
for your activity will restrict it to portrait mode.
For more info on the settings, see this.
When I switch orientations its like my phone restarts the program.
Well to be accurate, the currently visible Activity
is completely destroyed and recreated. Other components of your 'application' may or may not be impacted.
What causes this? How can I stop it?
It's by design and as for stopping it, you may or may not want to do that.
As has been mentioned, it is possible to specify that you want to handle 'configuration' changes (such as orientation) yourself or even force only one (e.g., landscape or portrait).
In many cases, however, an app developer may choose to change a layout based on whether a device is in one orientation or another. Some layouts may work fine in portrait but not in landscape (or vice versa) and the aim of the designed approach (to destroy / recreate the current visible Activity
) is meant to accommodate that.
If a dev chooses not to handle the configuration changes themself or force a specific orientation, the correct way to handle things is to make sure all data entered in 'volatile' UI elements (such as EditTexts) are correctly saved and recreated after orientation change.
To do this, understanding of the Activity
life-cycle is essential as is making use of the various Activity
methods that are called throughout the life-cycle to save / restore data.
Essential reading...
Runtime Changes
Activity Lifecycle
Application Fundamentals