Question

I require the currently set screen orientation in MonoDroid. It has to detect if it is either landscape, portrait or reversed-landscape and reversed-portrait.

Methods like WindowManager.DefaultDisplay.Rotation do not always return correct results.

Was it helpful?

Solution

I found the answer written in Java here: How do I get the CURRENT orientation (ActivityInfo.SCREEN_ORIENTATION_*) of an Android device?

This is the corresponding MonoDroid C# translation:

private ScreenOrientation GetScreenOrientation() {
    ScreenOrientation orientation;
    SurfaceOrientation rotation = WindowManager.DefaultDisplay.Rotation;

    DisplayMetrics dm = new DisplayMetrics();
    WindowManager.DefaultDisplay.GetMetrics(dm);

    if ((rotation == SurfaceOrientation.Rotation0 || rotation == SurfaceOrientation.Rotation180) && dm.HeightPixels > dm.WidthPixels
        || (rotation == SurfaceOrientation.Rotation90 || rotation == SurfaceOrientation.Rotation270) && dm.WidthPixels > dm.HeightPixels) {
        // The device's natural orientation is portrait
        switch (rotation) {
            case SurfaceOrientation.Rotation0:
                orientation = ScreenOrientation.Portrait;
                break;
            case SurfaceOrientation.Rotation90:
                orientation = ScreenOrientation.Landscape;
                break;
            case SurfaceOrientation.Rotation180:
                orientation = ScreenOrientation.ReversePortrait;
                break;
            case SurfaceOrientation.Rotation270:
                orientation = ScreenOrientation.ReverseLandscape;
                break;
            default:
                orientation = ScreenOrientation.Portrait;
                break;
        }
    } else {
        // The device's natural orientation is landscape or if the device is square
        switch (rotation) {
            case SurfaceOrientation.Rotation0:
                orientation = ScreenOrientation.Landscape;
                break;
            case SurfaceOrientation.Rotation90:
                orientation = ScreenOrientation.Portrait;
                break;
            case SurfaceOrientation.Rotation180:
                orientation = ScreenOrientation.ReverseLandscape;
                break;
            case SurfaceOrientation.Rotation270:
                orientation = ScreenOrientation.ReversePortrait;
                break;
            default:
                orientation = ScreenOrientation.Landscape;
                break;
        }
    }

    return orientation;
}

Pretty much code for such a simple and common task, but it works perfectly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top