Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid restarting activity when orientation changes on Android

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?

like image 870
chirag Avatar asked Dec 31 '10 06:12

chirag


People also ask

How do you prevent data from reloading and resetting when the screen is rotated?

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.

What happens to an activity when the screen orientation changes?

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() ).

What happens when orientation changes Android?

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.


2 Answers

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.

like image 192
Mike Avatar answered Oct 16 '22 18:10

Mike


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> 
like image 26
Vikas Avatar answered Oct 16 '22 19:10

Vikas