1
votes

Xamarin Android app that use the Xamarin Forms UI framework. I detect the screen orientation and want to only allow portrait and landscape for a specific Page but portrait only for all other pages.

I tried to call RequestOrientation but that force the orientation to stay the same and doesn't fire my orientation change notification again.

3
Do you allow other orientations than portrait orientation in Android solution properties? - Kuba

3 Answers

2
votes

Have a static property in your App.Xaml.cs

public static bool IsPortraitOnly { get; set; }

Set it to false in all pages and to true in the page you want it to be Portrait only.

In your MainActivity in android project, override the method OnConfigurationChanged :

    public override void OnConfigurationChanged(Configuration newConfig)
    {
        //using to prevent the OnCreate from firing when rotating or screen size is changing
        if (App.IsPortraitOnly)
        {
            RequestedOrientation = ScreenOrientation.Portrait;
            newConfig.Orientation = Orientation.Portrait;
        }
        base.OnConfigurationChanged(newConfig);
    } 

The following are the available orientation values in android :

public enum Orientation
{
    Landscape = 2,
    Portrait = 1,
    Square = 3,
    Undefined = 0
}
1
votes

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

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

you can use sizeChanged event.The SizeChanged event seems to get called exactly once as the user goes from portrait to landscape mode

 SizeChanged += (sender, e) => Content = IsPortrait(this) ? portraitView : landscapeView;
0
votes
RequestedOrientation = ScreenOrientation.Portrait;

If you write code on the code side, portrait mode is maintained.