我需要MonoDroid中当前设置的屏幕方向。它必须检测它是横向,纵向还是反向横向和反向纵向。
WindowManager.DefaultDisplay.Rotation等方法并不总能返回正确的结果。
答案 0 :(得分:0)
我在这里找到了用Java编写的答案:How do I get the CURRENT orientation (ActivityInfo.SCREEN_ORIENTATION_*) of an Android device?
这是相应的MonoDroid C#翻译:
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;
}
这是一个简单而常见的任务的代码,但它完美无缺。