Rotational Forces…On Your Android App


There have been several messages recently on the Android Google Groups related to rotation — the act of moving the display from portrait to landscape or vice versa. In the case of the T-Mobile G1, rotation should occur as part of sliding open the keyboard to do text entry. Today, we’ll take a peek at how rotation and the activity lifecycle work in concert, and what that means for you, the intrepid Android developer.

Some developers have been mystified with their application’s behavior when the display is rotated. Specifically, initialization code in onCreate() appears to happen every time the screen rotates.

The good news is that these developers are not crazy. onCreate() is called every time the screen rotates…because on a screen rotation, the activity is destroyed and created anew with access to the appropriate set of resources.

To examine this, let’s build a test application containing two fairly trivial activities. One (“parent”) has a button that launches the other (“child”), whereas the second has a button that calls finish() on itself.

The layouts of the two are all but identical, varying only in the label of the button:

[sourcecode language=’xml’]

About author

AndroidGuys 4683 posts

Founded on November 5, 2007, we've enjoyed bringing you the latest in Android news and rumors. Updated daily, we strive to deliver reviews, opinions, and updates on all things related to Android.