How to avoid restarting activities when rotating the screen in Android?

- Andrés Cruz

En español
How to avoid restarting activities when rotating the screen in Android?

Many times when testing our Android application that we are developing, either in the emulator incorporated by the ADT or in a physical/real device; We can see that when we rotate or rotate the screen, the activities are restarted, resulting in:

  • The texts in the fields are deleted.
  • Certain configurations or statuses of activities are removed.

Among others; this is because when the device's screen is rotated, the OnCreate method (which belongs to the life cycle of an Android application -see life cycle of activities in Android-) is called again following the basic life cycle from an Android application and therefore restarts; a small section of code in the AndroidManifest configuration allows us to solve this problem, indicating which activities we want to be restarted and which ones, for this we must add the following attribute in the activity tag:

android:configChanges="screenSize|orientation"

Giving a small more complete example of what was previously explained:

<activity android:name="com.cuc.cacu.MyTourActivity" android:configChanges="screenSize|orientation"></activity>

What does each of these attributes mean?

  • orientation: The screen orientation has changed; or what is the same, the user has rotated the screen.
  • screenSize: Occurs when you change the resolution or aspect of your screen (16:9 by 9:16 to cite an example); that is, when you switch between landscape and portrait (rotate or rotate the screen).

More information about the previous configurations:

Why not set all activities to not restart by default?

It depends on how we configure our activities; as you may know, when designing an activity for multiple screen resolutions and positions (landscape/portrait -see the following example on a mobile device if you don't know what the difference is-) we may need to define multiple layouts per activity:

multiple layouts en android

Which means that if you disable the restart of an activity that presents multiple layouts and we rotate (flip) the mobile device, the layout will not update.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.