XF - How lock the orientation of one page just for phone ?

DervoutDervout USUniversity

Hi,

I want to lock the orientation of one page in portrait. I made this and it work:

  1. Add a property OrientationRequest in my own ContentPage contol
  2. Use the property in the Renderer Android:
[assembly: ExportRenderer(typeof(MyContentPage), typeof(MyContentPageRenderer))]
namespace Core.Forms.Droid.Renderers
{
    public class MyContentPageRenderer : PageRenderer
    {
        private ScreenOrientation _previousOrientation = ScreenOrientation.Unspecified;

        protected override void OnWindowVisibilityChanged([GeneratedEnum] ViewStates visibility)
        {
            base.OnWindowVisibilityChanged(visibility);
            var activity = (Activity)Context;
            PageOrientation? orientation = ((MyContentPage)this.Element).OrientationRequest;
            if (visibility == ViewStates.Gone)
            {
                activity.RequestedOrientation = _previousOrientation;
            }
            else if (visibility == ViewStates.Visible && orientation != null)
            {
                if (_previousOrientation == ScreenOrientation.Unspecified)
                {
                    _previousOrientation = activity.RequestedOrientation;
                }
                switch (orientation)
                {
                    case PageOrientation.Portrait:
                        activity.RequestedOrientation = ScreenOrientation.Portrait;
                        break;
                    case PageOrientation.Landscape:
                        activity.RequestedOrientation = ScreenOrientation.Landscape;
                        break;
                }
            }
        }
    }
}

3.Define the property in my page:

<controls:MyContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         ...
         OrientationRequest="Portrait" >

But when I want to lock just for phone, the property is not set.

<controls:MyContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         ...>
  <controls:MyContentPage.OrientationRequest>
    <OnIdiom x:TypeArguments="controls:PageOrientation" Phone="Portrait"/>
  </controls:MyContentPage.OrientationRequest>

Am I doing something that should not do ?

Thanks,

Camille Dervout

Sign In or Register to comment.