Activity restart on rotation Android

Problem: Activity restart on rotation 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?

Solution 1: Activity restart on rotation Android

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.

Solution 2: Activity restart on rotation Android

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>

Solution 3: Activity restart on rotation Android

Add this to all of your activities in the manifest.

android:configChanges="orientation|screenSize"

Example:

<activity android:name=".activity.ViewActivity"
        android:label="@string/app_name"
        android:configChanges="orientation|screenSize"/>

Declare this in your AndroidManifest.xml

<activity android:name=".complex_examples.VideoPlayerActivity"
            android:configChanges="keyboard|keyboardHidden|orientation
                                  |screenSize|screenLayout|smallestScreenSize|uiMode"
            android:launchMode="singleTop"/>

But take careAndroid Developers Documentation says that you should do it only if there is no better options left.

Note: Using this attribute should be avoided and used only as a last resort. Please read Handling Runtime Changes for more information about how to properly handle a restart due to a configuration change.

If you are sure about doing it, you can handle the configuration changes by yourself in onConfigurationChanged() method.

Conclusion

I hope the Activity restart on rotation Android The solution would be useful for you to learn something new from this solution. If it helped you then don’t forget to bookmark our site for more Quiz Answers and solutions.

for more info

Leave a Reply

Your email address will not be published.