问题
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.
回答1:
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
}
回答2:
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;
回答3:
RequestedOrientation = ScreenOrientation.Portrait;
If you write code on the code side, portrait mode is maintained.
来源:https://stackoverflow.com/questions/41263942/xamarin-android-xamarin-forms-orientation-change