What happens when android screen rotates?

      No Comments on What happens when android screen rotates?

Rotating the android device changes the device configuration. Android replaces the current resources with the best suited resources for that screen orientation. Thats why when we add a resource in android we add different versions of that resource. For example an image can be added in four formats(hdpi, mdpi, xhdpi, xxhdpi). The below screen shot shows the same resource for different screen sizes.


Lets understand this with an example

For this example I have created two different layout files with the same name. One is present in the res/layout folder and other is in res/layout-land. Both the layouts contains just a TextView with different texts so that we can easily figure out which resource is loaded.

activity_main.xml in res/layout

activity_main.xml in res/layout-land

Watch the below video to see the above code in action

How android loads the different layout

When screen rotates, Android destroys the current activity and recreates it. Which means the Activity methods will be called in following order.

Destroys current activity with  onPause() => onStop() => onDestroy()

Creates same activity with different resources using  onCreate() => onStart() => onResume()

When onCreate method is called we call setContentView(R.layout.activity_main) in it. Which loads the new layout resource. And because it destroys the current activity your data on the screen will be lost.

Thats all what happens when android screen rotates. If you have any doubts or any suggestion or any feedback please leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *