我有一个Activity,需要锁定其方向
setRequestedOrientation(screenOrientation);
但我想获取方向更新,以便我可以对UI进行调整(想象一下HTC相机应用程序,当仅按钮图标更改方向时)。因此,我找到了这个类。它提供了0到360之间的方向值。如何过滤这些值,即找到完美的区间
[a, b]
,并且如果a<x<b
,则方向为横向或纵向?计算平均值?有任何提示吗?听起来您需要的代码只在设备方向改变为四个正常方向之一时才作出反应,而不是每个角度都作出反应。这将过滤方向,仅保留0、90、180和270度的值:
OrientationEventListener myOrientationEventListener;
int iOrientation;
myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL)
{
@Override
public void onOrientationChanged(int iAngle)
{ // 0 15 30 45 60 75, 90 105, 120, 135, 150, 165, 180, 195, 210, 225, 240, 255, 270, 285, 300, 315, 330, 345
final int iLookup[] = {0, 0, 0,90,90, 90,90, 90, 90, 180, 180, 180, 180, 180, 180, 270, 270, 270, 270, 270, 270, 0, 0, 0}; // 15-degree increments
if (iAngle != ORIENTATION_UNKNOWN)
{
int iNewOrientation = iLookup[iAngle / 15];
if (iOrientation != iNewOrientation)
{
iOrientation = iNewOrientation;
// take action on new orientation here
}
}
}
};
// To display if orientation detection will work and enable it
if (myOrientationEventListener.canDetectOrientation())
{
Toast.makeText(this, "Can DetectOrientation", Toast.LENGTH_LONG).show();
myOrientationEventListener.enable();
}
else
{
Toast.makeText(this, "Can't DetectOrientation", Toast.LENGTH_LONG).show();
}