我想通过实现 SensorEventListener 来检测设备屏幕方向,因为它的当前屏幕方向默认设置为纵向。我需要这样做,因为我的布局包括一些应该独立于其布局旋转的按钮,并且这样做的唯一方法(据我所知)是通过覆盖 onConfigurationChanged 并将相应的动画添加到每个屏幕方向。我不认为 OrientationEventListener 会起作用,因为设置的方向固定为纵向。那么如何从传感器本身检索屏幕方向或角度旋转呢?
问问题
739 次
1 回答
3
即使方向固定,OrientationEventListener 也可以工作;请参阅https://stackoverflow.com/a/8260007/1382108。它根据文档监控传感器。假设您定义了以下常量:
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 返回的内容,因此如果您有自然横向设备(平板电脑),则必须考虑到这一点,请参阅如何在 Android 上检查设备自然(默认)方向(即获取横向,例如 Motorola Charm 或翻转)。
@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);
}
}
}
于 2015-10-23T09:49:46.370 回答