Skip to content

Welcome to Mobile Orientation Orientation!

Mobile apps sometimes have to adjust to the user rotating the device from portrait mode to landscape mode and the reverse. For the most part, Xojo handles this for you. For Android projects, if you have locked controls properly and for iOS projects, if you have set the constraints properly, the controls will do the right thing when the device is rotated.

If there’s something you need to do in code when the orientation changes, you’re in luck. The MobileScreen class has an OrientationChanged event. When this event fires, that means the user has rotated their device and the orientation has changed. This is where your code would go should you need to respond to an orientation change.

Note: If you need to know when the screen has changed in size, that’s what the Resized event is for (at least on iOS – it’s not yet supported for Android).

What might not be immediately intuitive or obvious is that rotating your device does not automatically mean the orientation has changed. Consider the following example project that displays the Resized and OrientationChanged events in a table when they occur. While this is on iOS, it works the same way (without the Resized event) on Android. The device is starting in portrait mode.

We will focus on just the OrientationChanged events for now. It gets an initial OrientationChanged event. Then the user rotates their phone clockwise enough that the orientation is changed from portrait to landscape.

You can see that another OrientationChanged event has fired as you’d expect. Next the user rotates the phone clockwise again.

Now the phone is upside down. Notice, however, the orientation from the perspective of the OS has not changed. The layout is still in landscape orientation. This is not a bug. The device does not support portrait mode when the device is turned upside down. Thus the layout is still in landscape orientation and thus no OrientationChanged event has fired because there has been no orientation change.

Next the user rotates the phone clockwise yet again.

You might think that an OrientationChanged event would fire, but it doesn’t. Why not? Because as far as the OS is concerned, the layout is still in landscape orientation. It has not changed its orientation. Finally, the user rotates the device clockwise once last time.

This time the orientation has changed from landscape to portrait and thus the OrientationChanged event fired. Given that the initial OrientationChanged event fired when the app launched, out of the four 90 degree clockwise rotations, only two orientation changes occurred and thus only two OrientationChanged events fired.

This is one of those cases where what is initially intuitive turns out to be wrong until you look more closely at what is really going on.

Geoff Perlman is the Founder and CEO of Xojo. When he’s not leading the Xojo team he can be found playing drums in Austin, Texas and spending time with his family.