如何查看Android手机是横屏还是竖屏?


当前回答

如果你使用getResources(). getconfiguration()。在某些设备上,你会得到错误的方向。我们最初在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;
}

其他回答

当前配置,用于确定检索哪些资源,可以从resources的configuration对象中获得:

getResources().getConfiguration().orientation;

你可以通过查看它的值来检查方向:

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

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

Android SDK可以很好地告诉你:

getResources().getConfiguration().orientation

我认为使用getRotationv()没有帮助,因为 http://developer.android.com/reference/android/view/Display.html#getRotation%28%29 getRotation()返回屏幕从其“自然”方向的旋转。

所以除非你知道“自然”方向,旋转是没有意义的。

我找到了一个更简单的方法

  Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
  Point size = new Point();
  display.getSize(size);
  int width = size.x;
  int height = size.y;
  if(width>height)
    // its landscape

请告诉我这个人有什么问题吗?

It's also worth noting that nowadays, there's less good reason to check for explicit orientation with getResources().getConfiguration().orientation if you're doing so for layout reasons, as Multi-Window Support introduced in Android 7 / API 24+ could mess with your layouts quite a bit in either orientation. Better to consider using <ConstraintLayout>, and alternative layouts dependent on available width or height, along with other tricks for determining which layout is being used, e.g. the presence or not of certain Fragments being attached to your Activity.

我认为这个解决方法很简单

if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
  user_todat_latout = true;
} else {
  user_todat_latout = false;
}