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


当前回答

我认为使用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

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

其他回答

解决这个问题的另一种方法是不依赖于显示的正确返回值,而是依赖于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)

还有一种方法:

public int getOrientation()
{
    if(getResources().getDisplayMetrics().widthPixels>getResources().getDisplayMetrics().heightPixels)
    { 
        Toast t = Toast.makeText(this,"LANDSCAPE",Toast.LENGTH_SHORT);
        t.show();
        return 1;
    }
    else
    {
        Toast t = Toast.makeText(this,"PORTRAIT",Toast.LENGTH_SHORT);
        t.show();
        return 2;
    }       
}

用这种方法,

    int orientation = getResources().getConfiguration().orientation;
    String Orintaion = "";
    switch (orientation)
    {
        case Configuration.ORIENTATION_UNDEFINED: Orintaion = "Undefined"; break;
        case Configuration.ORIENTATION_LANDSCAPE: Orintaion = "Landscrape"; break;
        case Configuration.ORIENTATION_PORTRAIT:  Orintaion = "Portrait"; break;
        default: Orintaion = "Square";break;
    }

在字符串中,你有方向

使用getresource () .getConfiguration()。方向是正确的。

你只需要注意不同类型的景观,设备通常使用的景观和其他的。

还是不知道该怎么处理。

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.