Hello,
I want to force landscape mode only on some selected views and not for the whole App.
Do you want to set landscape mode in specific ContentPage?
If so, you can invoke native platform code to implement it.
You can use Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Locked;
and Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Landscape;
to lock the page to Landcape Mode.
You can use Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.User;
to reset it like following code.
public class DeviceOrientationService
{
public void SetOrientation()
{
#if ANDROID
Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Locked;
Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Landscape;
#endif
}
public void RestSetOrientation()
{
#if ANDROID
Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.User;
#endif
}
}
For example, you have page called page1, you need to Force Landcape Mode, you can execute deviceOrientationService.SetOrientation();
in OnAppearing
method and deviceOrientationService.RestSetOrientation();
in OnDisappearing
method.
protected override void OnAppearing()
{
base.OnAppearing();
DeviceOrientationService deviceOrientationService = new DeviceOrientationService();
deviceOrientationService.SetOrientation();
}
override protected void OnDisappearing()
{
base.OnDisappearing();
DeviceOrientationService deviceOrientationService = new DeviceOrientationService();
deviceOrientationService.RestSetOrientation();
}
I also want to have the forced landscape only ontablets not on phones.
You can use get the device type from the MAUI in app.xaml.cs
. If the type is Tablet, you can forced landscape like following code.
public App()
{
InitializeComponent();
MainPage = new AppShell();
DetectDeviceType();
}
private void DetectDeviceType()
{
if (DeviceInfo.Current.Idiom == DeviceIdiom.Tablet)
{
Console.WriteLine("The current device is a Tablet");
DeviceOrientationService deviceOrientationService = new DeviceOrientationService();
deviceOrientationService.SetOrientation();
}
}
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.