Hello,
Welcome to our Microsoft Q&A platform!
Is it possible to allow detection of device orientation change for only one page
If you set the ScreenOrientation = ScreenOrientation.Portrait
in the MainActivity.cs
to keep the only allow portrait. This answer is Yes
If you want to allow detection of device orientation change for only one page, You can an interface in PCL.
public interface IDetectScreen
{
void EnableDetectOrientation();
void CloseDetectOrientation();
}
Then achieve it in the Dependency service in android platform.
[assembly: Xamarin.Forms.Dependency(typeof(DetectScreenService))]
namespace AudioDemo.Droid
{
class DetectScreenService : IDetectScreen
{
public void CloseDetectOrientation()
{
MainActivity.Intance.RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
}
public void EnableDetectOrientation()
{
MainActivity.Intance.RequestedOrientation = Android.Content.PM.ScreenOrientation.Sensor;
}
}
}
MainActivity.Instance.
is a public static value .
public static MainActivity Instance;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
//set the value to Intance
Instance= this;
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
To use the above, subclass ContentPage and override the OnAppearing
and OnDisappearing
methods and subscribe to the DeviceDisplay.MainDisplayInfoChanged
event to detect and test that the change occurred as in the following code sample:
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
DeviceDisplay.MainDisplayInfoChanged += OnMainDisplayInfoChanged;
}
private void OnMainDisplayInfoChanged(object sender, DisplayInfoChangedEventArgs e)
{
var displayInfo = e.DisplayInfo;
var rotation = displayInfo.Rotation;
var displayOrientation = displayInfo.Orientation;
DisplayAlert("info", rotation + " " + displayOrientation, "OK");
}
protected override void OnAppearing()
{
base.OnAppearing();
DependencyService.Get<IDetectScreen>().EnableDetectOrientation();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
DependencyService.Get<IDetectScreen>().CloseDetectOrientation();
}
}
Best Regards,
Leon Lu
If the response is helpful, please click "Accept Answer" and upvote it.
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.