如何让度的Android设备的物理方向。 [英] How to get the Android device's physical orientation in degrees.
本文介绍了如何让度的Android设备的物理方向。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我必须使用类OrientationListener到从设备的角度。我想要得到-90°和90°之间的角度。我不知道该怎么做。
左图:90度,画面中间:0度右图:-90度
code
类OrientationListener实现SensorEventListener
{ @覆盖
公共无效onSensorChanged(SensorEvent事件)
{
角= Math.round(event.values [2]); 如果(角度θ0)
{
角=角* -1;
}
} @覆盖
公共无效onAccuracyChanged(传感器传感器,精度INT)
{
}
}
解决方案
这是一个工作的例子。
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState); TextView的电视=新的TextView(本);
的setContentView(电视); 显示显示=((窗口管理器)getSystemService(WINDOW_SERVICE))getDefaultDisplay()。
INT旋转= display.getRotation(); 串rotString =;
开关(旋转){
案例Surface.ROTATION_0:
rotString =画像;
打破;
案例Surface.ROTATION_90:
rotString =山水左;
打破;
案例Surface.ROTATION_180:
rotString =翻转画像;
打破;
案例Surface.ROTATION_270:
rotString =景观权;
打破;
} tv.setText(rotString);}
I know that I have to use the class OrientationListener to get the angle from the device. I want to get the angle between -90° and 90°. I don't know how to do it. picture on the left: 90 degree, picture in the middle: 0 degree and picture on the right: -90 degree
Code
class OrientationListener implements SensorEventListener
{
@Override
public void onSensorChanged(SensorEvent event)
{
angle = Math.round(event.values[2]);
if (angle < 0)
{
angle = angle * -1;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
}
解决方案
This is a working example.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
setContentView(tv);
Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
String rotString="";
switch(rotation) {
case Surface.ROTATION_0:
rotString="portrait";
break;
case Surface.ROTATION_90:
rotString="landscape left";
break;
case Surface.ROTATION_180:
rotString="flipped portrait";
break;
case Surface.ROTATION_270:
rotString="landscape right";
break;
}
tv.setText(rotString);
}
这篇关于如何让度的Android设备的物理方向。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文