如何在Xamarin.Forms中检测设备的屏幕方向?

12
如何在Xamarin Forms中检测屏幕方向的更改?我需要在方向更改时更改视图,我应该做什么才能触发方向更改?提供链接或示例代码将非常有帮助。

提前感谢


当屏幕方向改变时,将调用 OnCreate - GSerg
2
@GSerg 这只适用于Android系统.. - bkardol
2个回答

14

我尝试使用依赖注入,但目前还没有成功。现在,我是这样解决它的:

  • 使用 OnSizeAllocated(double, double) 来更改屏幕方向变化时的屏幕。
  • 使用单例来存储当前屏幕方向。

Xamarin.Forms 页面

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

    if (DeviceInfo.IsOrientationPortrait() && width > height || !DeviceInfo.IsOrientationPortrait() && width < height)
        {
            // Orientation got changed! Do your changes here
        }
}

单例类

public class DeviceInfo
{
    protected static DeviceInfo _instance;
    double width;
    double height;

    static DeviceInfo()
    {
        _instance = new DeviceInfo();
    }
    protected DeviceInfo()
    {
    }

    public static bool IsOrientationPortrait() 
    {
        return _instance.height > _instance.width;
    }

    public static void SetSize(double width, double height)
    {
        _instance.width = width;
        _instance.height = height;
    }
}

13

只需将此代码添加到您的页面或更好的是基础页面(BasePage)中:

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

1
需要应对不同方向的代码的有用提示,但这并没有展示如何在方向更改时触发某些操作 - 需要一些类型的事件监听器(或“on”方法)。 - ToolmakerSteve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接