我正在试验加速度计和陀螺仪。我在layout.xml中定义了一个简单的线视图,我想计算手机的当前角度,这样我就可以使用View.SetRotation()让线与地面平行。我找到了很多教程,但我无法让它发挥作用。
这是我的代码:
layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.main.camera3doit.TestActivity">
<TextView
android:text="angle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/angleText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textColor="#ffff0000"
android:textSize="30dp" />
<View
android:id="@+id/lineView"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:background="#ff01eb00" />
</RelativeLayout>
TestActivity.java
public class TestActivity extends Activity {
TextView angleText;
View line;
private SensorManager sensorManager;
private Sensor accelerometer;
private Sensor magnetometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
line = findViewById(R.id.lineView);
angleText = (TextView) findViewById(R.id.angleText);
}
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListenerer, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(sensorEventListenerer, magnetometer, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListenerer);
}
private SensorEventListener sensorEventListenerer = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
/*
*
*
*
* Here i want to do my calculations
* so i can find what rotation the line should have
*
*
*
*
*/
angleText.setText(phoneRotationDegrees);
line.setRotation(DegreesSoItIsParallelToTheGround);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}