【问题标题】:How to detect screen orientation of the device in Xamarin.Forms?如何在 Xamarin.Forms 中检测设备的屏幕方向?
【发布时间】:2014-08-30 15:51:29
【问题描述】:

如何检测 Xamarin Forms 中的屏幕方向变化?我需要改变对方向变化的看法,我应该怎么做才能触发方向变化的变化?提供链接或示例代码会很有帮助。

提前致谢

【问题讨论】:

  • OnCreate 在方向改变时被调用。
  • @GSerg 这只是安卓系统..

标签: xamarin cross-platform xamarin.forms


【解决方案1】:

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

  • 使用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;
    }
}

【讨论】:

    【解决方案2】:

    只需将此添加到您的页面,或者更好地添加到您的 BasePage:

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

    【讨论】:

    • 对于需要处理不同方向的代码的有用提示,尽管它没有显示如何在方向变化时触发某些操作 - 某种类型的事件侦听器(或需要“on”方法)。
    猜你喜欢
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 2011-06-14
    • 1970-01-01
    相关资源
    最近更新 更多