Search code examples
c#xamarin.formsdevice-orientation

How can I block rotation to only allow portrait mode in xamarin forms?


I need to block rotation on a specific page and this has to work both for Android and iOS.

I tried using NuGet Plugin.DeviceOrientation and adding the following code

protected override void OnAppearing()
        {
            base.OnAppearing();
            if (CrossDeviceOrientation.IsSupported) 
                CrossDeviceOrientation.Current.LockOrientation(Plugin.DeviceOrientation.Abstractions.DeviceOrientations.Portrait);
        }


protected override void OnDisappearing()
        {
            base.OnDisappearing();
            if (CrossDeviceOrientation.IsSupported) 
                CrossDeviceOrientation.Current.UnlockOrientation();
        }

but throws exception: System.NullReferenceException: 'Object reference not set to an instance of an object.'


Solution

  • For Xamarin.Forms, you could dependency service.

    Create a interface:

     public interface IRotate
    {
        void ForcePortrait();
    }
    

    Android:

    [assembly: Xamarin.Forms.Dependency(typeof(RoateHandler))]
    namespace RotatePage.Droid
    {
    class RoateHandler : IRotate
    {
        public void ForcePortrait()
        {
            ((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.Portrait;
        }
    }
    }
    

    iOS:

    [assembly: Xamarin.Forms.Dependency(typeof(RoateImplementation))]
    namespace RotatePage.iOS
    {
    class RoateImplementation : IRotate
    {
        public void ForcePortrait()
        {
            UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.Portrait), new NSString("orientation"));
        }
    }
    }
    

    Usage:

    DependencyService.Get().ForcePortrait();

    Screenshot:

    enter image description here