我目前正在尝试实现一个ScrollView,我希望通过RotationVectorSensor和SensorEventListener滚动包含的ImageView。
到目前为止,这是我的代码:
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.widget.HorizontalScrollView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor sensor;
private HorizontalScrollView scrollView;
private String TAG = MainActivity.class.getSimpleName();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
if (sensor != null) {
sensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
Log.d(TAG, "Sensor found.");
} else {
Log.e(TAG, "Sensor NOT found.");
Toast.makeText(this, "ROTATION_VECTOR Sensor not found",
Toast.LENGTH_LONG).show();
finish();
}
scrollView = (HorizontalScrollView) findViewById(R.id.panoramaScrollView);
Log.d(TAG, "Panorama Scroll View found.");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
Toast.makeText(this, "rotating Yippi!", Toast.LENGTH_LONG).show();
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
final float angle = event.values[2];
scrollView.post(new Runnable() {
public void run() {
if (scrollView != null) {
scrollView.scrollTo((int)angle, scrollView.getBottom());
Log.d(TAG, "scrollTo executed.");
}
}
});
}
}
@Override
public void onResume() {
super.onResume();
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
Log.d(TAG, "SensorListener registered");
}
@Override
public void onPause() {
super.onPause();
if (sensor != null) {
sensorManager.unregisterListener(this);
Log.d(TAG, "SensorListener unregistered");
}
}
}
Nullpointer 在传感器初始化后直接发生:
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
因此应用程序退出并打印:“未找到传感器”...
有什么我忘记了吗?
提前致谢!