如何检查Android手机是横屏还是竖屏?
发布于 2010-05-10 04:06:07
用于确定要检索哪些资源的当前配置可从资源的Configuration对象中获得:
getResources().getConfiguration().orientation;您可以通过查看其值来检查方向:
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
// In landscape
} else {
// In portrait
}更多信息可以在Android Developer中找到。
发布于 2011-06-04 18:11:06
如果你在某些设备上使用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;
}发布于 2013-02-18 12:00:21
解决这个问题的另一种方法是不依赖于显示的正确返回值,而是依赖于Android资源解析。
在res/values-land和res/values-port文件夹中创建包含以下内容的文件layouts.xml:
res/values-land/layouts.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="is_landscape">true</bool>
</resources>res/values-port/layouts.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="is_landscape">false</bool>
</resources>在您的源代码中,您现在可以访问当前方向,如下所示:
context.getResources().getBoolean(R.bool.is_landscape)https://stackoverflow.com/questions/2795833
复制相似问题