Checking Device Orientation

Use DependencyService to access device orientation from shared code

PDF for offline use:
Sample Code:
Related Samples:

Let us know how you feel about this.


0/250
Thanks for the feedback!

last updated: 2016-08

This article will guide you to use DependencyService to check the device orientation from shared code using the native APIs on each platform. This walkthrough is based on the existing DeviceOrientation plugin by Ali Özgür. See the GitHub repo for more information.

The application using DependencyService will have the following structure:

Note: It is possible to detect whether the device is in portrait or landscape orientation in shared code, as demonstrated in Device Orientation. The method described in this article uses native features to get more information about orientation, including whether the device is upside down.

Creating the Interface

First, create an interface in the shared code that expresses the functionality you plan to implement. For this example, the interface contains a single method:

namespace DependencyServiceSample.Abstractions
{
    public enum DeviceOrientations
    {
        Undefined,
        Landscape,
        Portrait
    }

    public interface IDeviceOrientation
    {
        DeviceOrientations GetOrientation();
    }
}

Coding against this interface in the shared code will allow the Xamarin.Forms app to access the device orientation APIs on each platform.

Note: Classes implementing the interface must have a parameterless constructor to work with the DependencyService.

iOS Implementation

The Interface must be implemented in each platform-specific application project. Note that the class has a parameterless constructor so that the DependencyService can create new instances:

using UIKit;
using Foundation;

namespace DependencyServiceSample.iOS
{
    public class DeviceOrientationImplementation : IDeviceOrientation
    {
        public DeviceOrientationImplementation(){ }

        public DeviceOrientations GetOrientation()
        {
            var currentOrientation = UIApplication.SharedApplication.StatusBarOrientation;
            bool isPortrait = currentOrientation == UIInterfaceOrientation.Portrait
                || currentOrientation == UIInterfaceOrientation.PortraitUpsideDown;

            return isPortrait ? DeviceOrientations.Portrait: DeviceOrientations.Landscape;
        }
    }
}

Finally, add this [assembly] attribute above the class (and outside any namespaces that have been defined), including any required using statements:

using UIKit;
using Foundation;
using DependencyServiceSample.iOS; //enables registration outside of namespace

[assembly: Xamarin.Forms.Dependency (typeof (DeviceOrientationImplementation))]
namespace DependencyServiceSample.iOS {
    ...

This attribute registers the class as an implementation of the IDeviceOrientation Interface, which means that DependencyService.Get<IDeviceOrientation> can be used in the shared code to create an instance of it.

Android Implementation

The following code implements IDeviceOrientation on Android:

using DependencyServiceSample.Droid;
using Android.Hardware;

namespace DependencyServiceSample.Droid
{
    public class DeviceOrientationImplementation : IDeviceOrientation
    {
        public DeviceOrientationImplementation() { }

        public static void Init() { }

        public DeviceOrientations GetOrientation()
        {
            IWindowManager windowManager = Android.App.Application.Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();

            var rotation = windowManager.DefaultDisplay.Rotation;
            bool isLandscape = rotation == SurfaceOrientation.Rotation90 || rotation == SurfaceOrientation.Rotation270;
            return isLandscape ? DeviceOrientations.Landscape : DeviceOrientations.Portrait;
        }
    }
}

Add this [assembly] attribute above the class (and outside any namespaces that have been defined), including any required using statements:

using DependencyServiceSample.Droid; //enables registration outside of namespace
using Android.Hardware;

[assembly: Xamarin.Forms.Dependency (typeof (DeviceOrientationImplementation))]
namespace DependencyServiceSample.Droid {
    ...

This attribute registers the class as an implementation of the IDeviceOrientaiton Interface, which means that DependencyService.Get<IDeviceOrientation> can be used in the shared code can create an instance of it.

Windows Phone and Universal Windows Platform Implementation

The following code implements the IDeviceOrientation interface on Windows Phone and the Universal Windows Platform:

namespace DependencyServiceSample.WindowsPhone
{
    public class DeviceOrientationImplementation : IDeviceOrientation
    {
        public DeviceOrientationImplementation() { }

        public DeviceOrientations GetOrientation()
        {
            var orientation = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Orientation;
            if (orientation == Windows.UI.ViewManagement.ApplicationViewOrientation.Landscape) {
                return DeviceOrientations.Landscape;
            }
            else {
                return DeviceOrientations.Portrait;
            }
        }
    }
}

Add the [assembly] attribute above the class (and outside any namespaces that have been defined), including any required using statements:

using DependencyServiceSample.WindowsPhone; //enables registration outside of namespace

[assembly: Dependency(typeof(DeviceOrientationImplementation))]
namespace DependencyServiceSample.WindowsPhone {
    ...

This attribute registers the class as an implementation of the DeviceOrientationImplementation Interface, which means that DependencyService.Get<IDeviceOrientation> can be used in the shared code can create an instance of it.

Implementing in Shared Code

Now we can write and test shared code that accesses the IDeviceOrientation interface. This simple page includes a button that updates its own text based on the device orientation. It uses the DependencyService to get an instance of the IDeviceOrientation interface – at runtime this instance will be the platform-specific implementation that has full access to the native SDK:

public MainPage ()
{
    var orient = new Button {
        Text = "Get Orientation",
        VerticalOptions = LayoutOptions.CenterAndExpand,
        HorizontalOptions = LayoutOptions.CenterAndExpand,
    };
    orient.Clicked += (sender, e) => {
       var orientation = DependencyService.Get<IDeviceOrientation>().GetOrientation();
       switch(orientation){
           case DeviceOrientations.Undefined:
                orient.Text = "Undefined";
                break;
           case DeviceOrientations.Landscape:
                orient.Text = "Landscape";
                break;
           case DeviceOrientations.Portrait:
                orient.Text = "Portrait";
                break;
       }
    };
    Content = orient;
}

Running this application on iOS, Android, or the Windows platforms and pressing the button will result in the the button's text updating with the device's orientation.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.