Middle
Is it possible to make an activity not recreated on screen rotation?
sobes.tech AI
Answer from AI
Yes, it is possible. There are two main ways.
-
Declare
configChangesin the manifest: InAndroidManifest.xml, add the attributeandroid:configChanges="orientation|screenSize"to the<activity>.<activity android:name=".MainActivity" android:configChanges="orientation|screenSize" />In this case, the activity is not recreated, but the method
onConfigurationChanged()is called, which should be overridden to handle configuration changes.override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) // Handle changes, for example: // if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { // // Changed to landscape orientation // } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { // // Changed to portrait orientation // } } -
Fix the screen orientation: You can set a fixed orientation for the activity by adding the attribute
android:screenOrientationin the manifest.<activity android:name=".MainActivity" android:screenOrientation="portrait" />or
<activity android:name=".MainActivity" android:screenOrientation="landscape" />In this case, the activity's orientation will not change regardless of device rotation, and it will not be recreated.