如何使用 SensorEventListener 检测设备方向?

How to detect the device orientation with SensorEventListener?

我想通过实现 SensorEventListener 来检测设备屏幕方向,因为它的当前屏幕方向默认设置为纵向。我需要这样做,因为我的布局包含一些按钮,这些按钮应该独立于它们的布局旋转,唯一的方法(据我所知)是覆盖 onConfigurationChanged 并向每个屏幕方向添加相应的动画。我不认为 OrientationEventListener 会起作用,因为设置的方向固定为纵向。那么如何从传感器本身检索屏幕方向或角度旋转?

即使方向固定,OrientationEventListener 也可以工作;参见 。它根据文档监控传感器。 假设您定义了以下常量:

private static final int THRESHOLD = 40;
public static final int PORTRAIT = 0;
public static final int LANDSCAPE = 270;
public static final int REVERSE_PORTRAIT = 180;
public static final int REVERSE_LANDSCAPE = 90;
private int lastRotatedTo = 0;

数字对应于 OrientationEventListener returns,因此如果您有自然景观设备(平板电脑),则必须考虑到这一点,请参阅 How to check device natural (default) orientation on Android (i.e. get landscape for e.g., Motorola Charm or Flipout)

 @Override
public void onOrientationChanged(int orientation) {
    int newRotateTo = lastRotatedTo;
    if(orientation >= 360 + PORTRAIT - THRESHOLD && orientation < 360 ||
            orientation >= 0 && orientation <= PORTRAIT + THRESHOLD)
        newRotateTo = 0;
    else if(orientation >= LANDSCAPE - THRESHOLD && orientation <= LANDSCAPE + THRESHOLD)
        newRotateTo = 90;
    else if(orientation >= REVERSE_PORTRAIT - THRESHOLD && orientation <= REVERSE_PORTRAIT + THRESHOLD)
        newRotateTo = 180;
    else if(orientation >= REVERSE_LANDSCAPE - THRESHOLD && orientation <= REVERSE_LANDSCAPE + THRESHOLD)
        newRotateTo = -90;
    if(newRotateTo != lastRotatedTo) {
        rotateButtons(lastRotatedTo, newRotateTo);
        lastRotatedTo = newRotateTo;
    }
}

rotateButtons 的功能类似于:

public void rotateButtons(int from, int to) {

    int buttons[] = {R.id.buttonA, R.id.buttonB};
    for(int i = 0; i < buttons.length; i++) {
        RotateAnimation rotateAnimation = new RotateAnimation(from, to, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setInterpolator(new LinearInterpolator());
        rotateAnimation.setDuration(200);
        rotateAnimation.setFillAfter(true);
        View v = findViewById(buttons[i]);
        if(v != null) {
            v.startAnimation(rotateAnimation);
        }
    }
}