Check orientation on Android phone

2018-12-31 08:02发布

How can I check if the Android phone is in Landscape or Portrait?

22条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 09:06

such this is overlay all phones such as oneplus3

public static boolean isScreenOriatationPortrait(Context context) {
         return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
         }

right code as follows:

public static int getRotation(Context context){
        final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();

        if(rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180){
            return Configuration.ORIENTATION_PORTRAIT;
        }

        if(rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270){
            return Configuration.ORIENTATION_LANDSCAPE;
        }

        return -1;
    }
查看更多
若你有天会懂
3楼-- · 2018-12-31 09:07

there are many ways to do this , this piece of code works for me

 if (this.getWindow().getWindowManager().getDefaultDisplay()
                .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
             // portrait mode
} else if (this.getWindow().getWindowManager().getDefaultDisplay()
                .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                      // landscape
        }
查看更多
春风洒进眼中
4楼-- · 2018-12-31 09:07

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.

查看更多
ら面具成の殇う
5楼-- · 2018-12-31 09:08

i think using getRotationv() doesn't help because http://developer.android.com/reference/android/view/Display.html#getRotation%28%29 getRotation() Returns the rotation of the screen from its "natural" orientation.

so unless you know the "natural" orientation, rotation is meaningless.

i found an easier way,

  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

please tell me if there is a problem with this someone?

查看更多
登录 后发表回答