我正在尝试在eclipse中编写一个Android程序。该程序的想法是,TextView
如果设备恰好旋转 180 度(我认为是在 xy 平面上?),则显示“设备已翻转”的消息。我正在使用旋转传感器并尝试在onSensorChanged
事件中编写我的代码。目前,此代码应该在检测到任何旋转时更改 TextView,但事实并非如此。
所以我的问题很简单:
- 给定任何旋转,我如何让 textview 改变?
- 然后如何将其应用于 180 度的旋转?
package com.example.rotation2;
import android.hardware.*;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
TextView message;
private SensorManager mSensorManager;
private Sensor rotation;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView message = ((TextView) findViewById(R.id.message_view));
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
rotation = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
if (rotation != null){
// Success! There's a rotation sensor.
message.setText(R.string.compatible);
}
else {
// Failure! No rotation sensor.
message.setText(R.string.incompatible);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
@Override
public void onSensorChanged(SensorEvent event) {
message.setText(R.string.rotated);
}
}