I am creating an Android app in which I'm drawing a view on a canvas. When the device's orientation changes, the activity restarts. I don't want it to.
How can I avoid restarting the activity when the orientation changes?
Prevent Activity to recreated Most common solution to dealing with orientation changes by setting the android:configChanges flag on your Activity in AndroidManifest. xml. Using this attribute your Activities won't be recreated and all your views and data will still be there after orientation change. Save this answer.
Some device configurations can change during runtime (such as screen orientation, keyboard availability, and when the user enables multi-window mode). When such a change occurs, Android restarts the running Activity ( onDestroy() is called, followed by onCreate() ).
When you rotate your device and the screen changes orientation, Android usually destroys your application's existing Activities and Fragments and recreates them . Android does this so that your application can reload resources based on the new configuration.
There are various ways to do it, but as given here, using
android:configChanges="keyboardHidden|orientation|screenSize"
allows you to listen for the config changes. You then respond to these changes by overriding onConfigurationChanged
and calling setContentView
.
This is the way I've been doing it, but I'd be interested to know other people's thoughts.
Define your activity in the AndroidManifest.xml like this:
<activity android:name="com.name.SampleActivity" android:configChanges="keyboardHidden|orientation|screenSize" android:icon="@drawable/sample_icon" android:label="@string/sample_title" android:screenOrientation="portrait" > </activity>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With