在 Android 手机上检查方向

新手上路,请多包涵

如何检查 Android 手机是横向还是纵向?

原文由 Mohit Deshpande 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 603
2 个回答

用于确定要检索哪些资源的当前配置可从资源的 Configuration 对象获得:

 getResources().getConfiguration().orientation;

您可以通过查看其值来检查方向:

 int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
    // In landscape
} else {
    // In portrait
}

更多信息可以在 Android 开发者 中找到。

原文由 hackbod 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您在某些设备上使用 getResources().getConfiguration().orientation,您会弄错。我们最初在 http://apphance.com 中使用了这种方法。感谢 Apphance 的远程日志记录,我们可以在不同的设备上看到它,我们看到碎片在这里发挥了作用。我看到了奇怪的情况:例如在 HTC Desire HD 上交替纵向和方形(?!):

 CONDITION[17:37:10.345] screen: rotation: 270 orientation: square
CONDITION[17:37:12.774] screen: rotation: 0 orientation: portrait
CONDITION[17:37:15.898] screen: rotation: 90
CONDITION[17:37:21.451] screen: rotation: 0
CONDITION[17:38:42.120] screen: rotation: 270 orientation: square

或者根本不改变方向:

 CONDITION[11:34:41.134] screen: rotation: 0
CONDITION[11:35:04.533] screen: rotation: 90
CONDITION[11:35:06.312] screen: rotation: 0
CONDITION[11:35:07.938] screen: rotation: 90
CONDITION[11:35:09.336] screen: rotation: 0

另一方面, width() 和 height() 总是正确的(它被窗口管理器使用,所以它应该更好)。我想说最好的办法是始终检查宽度/高度。如果你想一想,这正是你想要的 - 知道宽度是否小于高度(纵向),相反(横向)或者它们是否相同(正方形)。

然后归结为这个简单的代码:

 public int getScreenOrientation()
{
    Display getOrient = getWindowManager().getDefaultDisplay();
    int orientation = Configuration.ORIENTATION_UNDEFINED;
    if(getOrient.getWidth()==getOrient.getHeight()){
        orientation = Configuration.ORIENTATION_SQUARE;
    } else{
        if(getOrient.getWidth() < getOrient.getHeight()){
            orientation = Configuration.ORIENTATION_PORTRAIT;
        }else {
             orientation = Configuration.ORIENTATION_LANDSCAPE;
        }
    }
    return orientation;
}

原文由 Jarek Potiuk 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题