Sobes.tech
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.

  1. Declare configChanges in the manifest: In AndroidManifest.xml, add the attribute android: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
        // }
    }
    
  2. Fix the screen orientation: You can set a fixed orientation for the activity by adding the attribute android:screenOrientation in 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.

Is it possible to make an activity not recreated on… - sobes.tech