首页 > 解决方案 > 如何根据移动设备的方向更改(感知)Xamarin 表单的方向?

问题描述

我创建了一个 Xamarin 跨平台应用程序,它只会打开摄像头进行录制,但摄像头只能在横向模式下打开,即使用户将手机保持在纵向模式,也会出现一条弹出消息,因为请打开横向视图中的应用程序。

我无法感知移动设备处于横向模式或纵向模式的方向。当我运行我的应用程序时,它总是在纵向模式下获取移动设备的宽度和高度,而不是基于方向。

protected override void OnSizeAllocated(double width, double height) {
if (height > width) {
    IsPotrait = true;
}
else if (width > height) //Landscape mode
{
    IsPotrait = false;
}
base.OnSizeAllocated(width, height);
}

 protected async override void OnAppearing() {

if (IsPotrait) {
    DisplayAlert("Error", "Please hold up your phone for Landscape 
                         view.", "OK");
    return;
}
else {
    OpenCamera();
}

}

 public void OpenCamera() {
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakeVideoSupported) {
    DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
    return;
}

var file = CrossMedia.Current.TakeVideoAsync(new Plugin.Media.Abstractions.StoreVideoOptions {
    Name = "video.mp4",
    Directory = "DefaultVideos"
});

if (file == null) return;

DisplayAlert("Video Recorded", "Location", "OK");
}

标签: xamarinxamarin.android

解决方案


在启动画面中,使用高度和宽度检查设备方向。使用下面的代码

protected override void OnSizeAllocated(double width, double height)
{
    base.OnSizeAllocated(width, height);

    if (height > width ) //It means portrait mode
        {
            //Show popup here
        }
    else if(width > height)//Landscape mode
        {

        }
}

推荐阅读