【问题标题】:Detect orientation using javascript on android devices在 android 设备上使用 javascript 检测方向
【发布时间】:2012-04-12 21:02:20
【问题描述】:

使用来自this question 的一些代码我设置了一些代码来检测安卓设备何时旋转。它适用于华硕平板电脑(4.0.3)和两个模拟器(4.0.3 和 2.1),但对于 kindle fire(2.3.4)和 droidx(2.3.4),它会切换宽度和高度。

代码:

<script type="text/javascript">
    var supportsOrientationChange = "onorientationchange" in window,orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

    window.addEventListener(orientationEvent, function() {
        alert("The rotation is " + window.orientation + " and the resolution is " + screen.width + " x " + screen.height);
        modRule();
    }, false);
</script>

华硕平板电脑的输出

把它放在看起来像风景的地方:

旋转为0,分辨率为1280 x 800

肖像

旋转为-90,分辨率为800 x 1280

Kindle Fire 的输出

风景

旋转为 90,分辨率为 600 x 819

肖像:

旋转为0,分辨率为1024 x 395

droidx 的输出

风景:

旋转90,分辨率320x488

肖像:

旋转为0,分辨率为569x239

有办法吗

a) 让 javascript 检测是否应该使用高度而不是宽度或宽度而不是高度

b) 让设备报告其宽度和高度的正确值?

【问题讨论】:

    标签: java javascript android


    【解决方案1】:

    又找了一会儿,我发现这是 2.2 和 2.3 操作系统的错误。我通过将此代码放入我的应用程序中修复了 2.3.4 的错误。

    browser = (WebView)findViewById(R.id.webBrowser);
    browser.setBackgroundColor(Color.BLACK);
    WebSettings webSettings = browser.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUserAgentString("Android " + android.os.Build.VERSION.SDK);//this is so the JavaScript knows what version of the OS I'm using
    

    然后检测我是否处于横向模式:

    var uagent = navigator.userAgent.toLowerCase();
    function isLandscape()
    {
        var width = screen.width;
        var height = screen.height;
        if (isBugged())
        {
            var temp = width;
            width = height;
            height = temp;
        }
        var landscape = width > height;
        return landscape;
    }
    
    function isBugged()
    {
        return uagent == "android 10"
    }
    

    如果这还不够令人困惑,那么当身体最初加载时,它是否处于横向模式是正确的。所以我不得不绕过我自己的解决方法。

    <body onload="if(isBugged()){uagent = 'bypass';}/*code that depends on isLandscape()*/;uagent = navigator.userAgent.toLowerCase();">
    

    这是一个真正的痛苦,比应该做的工作要多得多。特别是因为它适用于 2.1 而不是 2.3.4。真的很沮丧,但这就是我所拥有的。目前,我只检查 sdk 10,我将很快添加对其他错误版本的检查。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多