January 4, 2015 .net spout

Handling Orientation Changes in Xamarin.Forms Apps

By default, Xamarin.Forms handles orientation changes for you automatically, e.g.



Xamarin.Forms handles orientation changes automatically

In this example, the labels are above the text entries in both the portrait and the landscape orientation, which Xamarin.Forms can do without any help from me. However, what if I want to put the labels to the left of the text entries in landscape mode to take better advantage of the space? Further, in the general case, you may want to have different layouts for each orientation. To be able to do that, you need to be able to detect the device’s current orientation and get a notification when it changes. Unfortunately, Xamarin.Forms provides neither, but luckily it’s not hard for you to do it yourself.

Finding the Current Orientation

To determine whether you’re in portrait or landscape mode is pretty easy:

static bool IsPortrait(Page p) { return p.Width < p.Height; }

This function makes the assumption that portrait mode has a smaller width. This doesn’t work for all future imaginable devices, of course, but in the case of a square device, you’ll just have to take your changes I guess.

Orientation Change Notifications

Likewise, Xamarin.Forms doesn’t have any kind of a OrientationChanged event, but I find that handling SizeChanged does the trick just as well:

SizeChanged += (sender, e) => Content = IsPortrait(this) ? portraitView : landscapeView;

The SizeChanged event seems to get called exactly once as the user goes from portrait to landscape mode (at least in my debugging, that was true). The different layouts can be whatever you want them to be. I was able to use this technique and get myself a little extra vertical space in my landscape layout:


Using a custom layout to put the labels on the left of the text entries instead of on top 

Of course, I could use this technique to do something completely differently in each orientation, but I was hoping that the two layouts made sense to the user and didn’t even register as special, which Xamarin.Forms allowed me to do.