Check orientation on Android phone

前端 未结 23 1596
庸人自扰
庸人自扰 2020-11-22 06:26

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

23条回答
  •  北海茫月
    2020-11-22 07:15

    You can use this (based on here) :

    public static boolean isPortrait(Activity activity) {
        final int currentOrientation = getCurrentOrientation(activity);
        return currentOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT || currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    }
    
    public static int getCurrentOrientation(Activity activity) {
        //code based on https://www.captechconsulting.com/blog/eric-miles/programmatically-locking-android-screen-orientation
        final Display display = activity.getWindowManager().getDefaultDisplay();
        final int rotation = display.getRotation();
        final Point size = new Point();
        display.getSize(size);
        int result;
        if (rotation == Surface.ROTATION_0
                || rotation == Surface.ROTATION_180) {
            // if rotation is 0 or 180 and width is greater than height, we have
            // a tablet
            if (size.x > size.y) {
                if (rotation == Surface.ROTATION_0) {
                    result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                } else {
                    result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                }
            } else {
                // we have a phone
                if (rotation == Surface.ROTATION_0) {
                    result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                } else {
                    result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                }
            }
        } else {
            // if rotation is 90 or 270 and width is greater than height, we
            // have a phone
            if (size.x > size.y) {
                if (rotation == Surface.ROTATION_90) {
                    result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                } else {
                    result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                }
            } else {
                // we have a tablet
                if (rotation == Surface.ROTATION_90) {
                    result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                } else {
                    result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                }
            }
        }
        return result;
    }
    

提交回复
热议问题