Android 自然传感器方向帮助 [英] Android natural sensor orientation help
问题描述
我正在尝试实现 Reto Meier 推荐的保持屏幕方向不变的方法.他在 Google IO 期间演讲的幻灯片(参见 #23)可以在 Android 提示:在哪里下载幻灯片和代码片段.
I am trying to accomplish Reto Meier's recommended way for keeping the screen orientation from changing. The slides from his talk during Google IO (see #23) can be found in Android Protips: Where to Download the Slides and Code Snippets.
我已逐步完成代码并设置了值,但屏幕方向仍会发生变化.仅供参考,我在应用程序中注册了这个监听器.
I have stepped through the code and it setting the values, but the screen orientation still changes. FYI, I register this listener in the Application.
这是我的代码:
final SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sm.registerListener(
new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
final WindowManager wm = (WindowManager) getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE);
final Display display = wm.getDefaultDisplay();
int x = SensorManager.AXIS_X;
int y = SensorManager.AXIS_Y;
switch (display.getRotation()) {
case Surface.ROTATION_90:
x = SensorManager.AXIS_Y;
y = SensorManager.AXIS_MINUS_X;
break;
case Surface.ROTATION_180:
y = SensorManager.AXIS_MINUS_Y;
break;
case Surface.ROTATION_270:
x = SensorManager.AXIS_MINUS_Y;
y = SensorManager.AXIS_MINUS_X;
break;
case Surface.ROTATION_0:
default:
break;
}
SensorManager.remapCoordinateSystem(sensorEvent.values, x, y, new float[] {});
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}, sm.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_NORMAL);
推荐答案
所有 30 多行当前不起作用的代码都可以替换为 AndroidManifest.xml
文件中的一些 XML 值.
All 30+ lines of code that currently are not working can be replaced with some XML values in your AndroidManifest.xml
file.
我们都见过
<activity android:name=".YourActivity" android:screenOrientation="portrait" ></activity>
而且我们都知道这不适用于具有默认横向方向的平板电脑.但是你们有多少人看过这个?
and we all know that doesn't work well with tablets that have a default orientation of landscape. But how many of you have seen this?
<activity android:name=".YourActivity" android:screenOrientation="nosensor" ></activity>
基本上它使设备的方向不会响应传感器.因此,如果您的默认设置是横向或纵向,则它不会改变.我已经在我的 Droid X 和 Xoom 并且它的工作原理与我预期的一样.
Basically it makes it so that the device's orientation doesn't respond to the sensor. So if your default is landscape or portrait it won't change. I have tested it on my Droid X and on a Xoom and it works like I would have expected it to.
我希望这能帮助其他人.
I hope this helps others.
这篇关于Android 自然传感器方向帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!