如何检查 Android 手机是横向还是纵向?
原文由 Mohit Deshpande 发布,翻译遵循 CC BY-SA 4.0 许可协议
如何检查 Android 手机是横向还是纵向?
原文由 Mohit Deshpande 发布,翻译遵循 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 许可协议
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
3 回答1.7k 阅读✓ 已解决
用于确定要检索哪些资源的当前配置可从资源的
Configuration
对象获得:您可以通过查看其值来检查方向:
更多信息可以在 Android 开发者 中找到。