WindowManager.DefaultDisplay.Rotation始终为零

时间:2014-07-30 12:39:51

标签: android xamarin

我正在使用Xamarin Android应用程序,该应用程序大部分都在纵向模式下运行。但是,现在我们正在添加功能,如果用户旋转设备,他们将在横向模式下获得另一个视图。

我的问题是,当我尝试使用以下代码片段时,无论我如何旋转设备,旋转始终具有值SurfaceRotation.Rotation0(即0)。

var windowManager = Application.Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
var rotation = windowManager.DefaultDisplay.Rotation; // Always gives zero

我在FragmentView中执行此代码(继承自MvxFragment继承的基类)。我设法使用OrientationEventListener获取一些代码,如下所示,但这不是理想的。我想利用默认的Android行为来旋转设备,如果可能的话,不要定义我自己的角度范围:

// This works!
public override void OnOrientationChanged(int orientation)
    {
    if (app.IsPortrait && ((orientation >= 85 && orientation <= 95) || (orientation >= 265 && orientation <= 275)))
    {
        Mvx.Trace("Send message to open new view in landscape mode");           
    }
    else if (!app.IsPortrait && (orientation < 85 || (orientation > 95 && orientation < 265 ) || orientation > 275))
    {
        Mvx.Trace("Send message to close the landscape view");      
    }
}

我使用连接的LGE Nexus 5设备和带有相同结果的Samsung GT-19300进行测试。两台设备都启用了自动旋转屏幕。我有一个UI(而不是问题in this thread)。我添加了

android:configChanges="orientation"

到我的清单。声明活动时,每个视图都设置正确的方向(例如,使用ScreenOrientation = ScreenOrientation.Portrait)。我错过了什么吗?

提前致谢!

大卫

1 个答案:

答案 0 :(得分:1)

我意识到当您通过设置ScreenOrientation = ScreenOrientation.Portrait(例如)指定活动的方向时,旋转(windowManager.DefaultDisplay.Rotation)始终为零,因为屏幕内容尚未相对于设备 - 无论设备的物理方向如何。

因此,为了解决我的问题,我删除了Activity的ScreenOrientation设置。这意味着当旋转设备时,内容也会旋转(根据默认的Android行为),当发生这种情况时,DefaultDisplay.Rotation的值将按预期设置。这允许我在OrientationEventListener,OnOrientationChanged事件中使用以下代码:

if (app.IsPortrait && (rotation == ScreenOrientation.Landscape || rotation == ScreenOrientation.ReverseLandscape))
{
        Mvx.Trace("Send message to open new view in landscape mode");
}
else if (!app.IsPortrait && (rotation == ScreenOrientation.Portrait || rotation == ScreenOrientation.ReversePortrait))
{
        Mvx.Trace("Send message to close the landscape view"); 
}

大卫