RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Developing Orientation-Aware Android Applications

Even though users take device landscape changes for granted, these changes remain challenging for developers to program. This article outlines a few tricks that will save you time when programming for an Android device.

ost modern, self-respecting mobile operating systems in today's market support different screen orientations based on the position of the device. Android is no exception. While this feature is often taken for granted, it's something on which developers spend extra time, ensuring that their applications work flawlessly regardless of screen orientation. This article will show you how screen orientation works in Android and some techniques to make your life easier.

Default Behavior for the Android G1

Create a new Android project and name it OrientationAware. For today's current Android device (which at the time of writing is the T-Mobile G1), the screen orientation changes only when the keyboard is opened or closed. When the keyboard is closed, the screen is displayed in portrait mode; when it is opened, the screen orientation changes to landscape.

To test the concepts discussed in this article, connect the G1 to your computer. In Eclipse, press F11 to deploy the application that you have just created to the G1. Figure 1 shows the UI of the application when the keyboard is closed. When the keyboard is opened, the orientation changes automatically to landscape mode, as shown in Figure 2.

Figure 1. Portrait: Here's the device display in portrait mode.
Figure 2. Landscape: Here's the device display in landscape mode.

Figure 3. Error: This is an activity that does not know how to react to a change in orientation.

Reacting to changes in screen orientation is important because it affects the look of your UI. The left side of Figure 3 shows an application designed to display in portrait mode. However, if special care is not taken to adapt the UI for landscape mode, it will look like the right side of Figure 3 when the device changes to landscape mode.

There are three general techniques you can employ to handle changes in screen orientation:

  • Anchoring: The easiest way is to "anchor" your views to the four edges of the screen—when the screen orientation changes, the views can anchor neatly to the edges.
  • Centralizing: Like anchoring, if your activity has only a few views, you might want to consider centralizing your views so that they are always displayed in the center of the screen.
  • Resizing and Repositioning: Anchoring and centralizing are simple techniques to ensure views can handle changes in screen orientation. The ultimate is resizing each and every view according to the current screen orientation.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date