描述
我有一个活动,它在表面视图上显示相机预览。由于它不断扫描QR代码,因此我不希望它在方向更改时重新启动,因此方向被锁定为肖像。
我的问题是,我需要在屏幕底部向用户显示说明。由于屏幕被锁定在一个方向上,我没有被通知新方向,因为活动没有被重绘。因此,无论手机处于纵向,反向纵向,横向还是反向横向,说明都被呈现在同一位置。
为了解决这个问题,我连接到传感器管理器以实时读取方向。(请参见下面的代码)读入后,我自行计算方向,并根据发送给我的每个更新所需移动我的说明。这对我一直有效,直到最近在Asus Transformer Prime和Xoom平板电脑上测试它。平板电脑将方向返回为“90”表示纵向,而其他两个手机则为“0”。因此,如下所示,我检查平板电脑(大屏幕)并减去额外的90度。
问题
问题是新的Nexus 7平板电脑没有这种额外偏差。在肖像中,它返回“0”,但我将其检测为平板电脑,因此减去90度,因此结果为270,并且它将我的说明放置在平板电脑处于横向模式的位置。我认为背后的原因是Xoom / Transformer设计用于横向使用,Nexus用于肖像,但除非我知道所有受影响的设备,否则这没有帮助。
问题
是否有一种可靠的方法来检测所有设备的方向并“实时”返回结果,就像下面的代码一样,但考虑到设备的默认方向(即手机+Nexus 7为肖像,但大多数平板电脑为横向)?
当前代码
boolean large = ((getBaseContext().getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
boolean xlarge = ((getBaseContext().getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
isTablet = large || xlarge;
myOrientationEventListener = new OrientationEventListener(getBaseContext(), SensorManager.SENSOR_DELAY_NORMAL)
{
@Override
public void onOrientationChanged(int orientation)
{
if (orientation == -1)
{
return;
}
if (isTablet)
{
orientation += -90;
if (orientation < 0) // keep the result between 0-360
{
orientation += 360;
}
}
// Work out the orientation
if (orientation >= 60 && orientation <= 140)
{
screenOrientation = ScreenOrientation.Landscape_Reversed;
}
else if (orientation >= 140 && orientation <= 220)
{
screenOrientation = ScreenOrientation.Portrait_Reversed;
}
else if (orientation >= 220 && orientation <= 300)
{
screenOrientation = ScreenOrientation.Landscape;
}
else
{
screenOrientation = ScreenOrientation.Portrait;
}
//... Do stuff with new orientation here
}
};