使用Android运动传感器,我想用传感器水平滚动图像。我的图像比屏幕大,所以我将图像设置在他的中心位置,然后从左向右水平移动设备。 不幸的是它不能正确滚动。我应该使用哪种传感器?陀螺仪还是加速度计?以及如何正确地在x轴上移动?
private SensorManager mSensorManager;
private Sensor mSensor;
private HorizontalScrollView hview;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
hview = (HorizontalScrollView) this.findViewById(R.id.hview);
hview.setSmoothScrollingEnabled(true);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_GYROSCOPE){
float xAxis = sensorEvent.values[0];
hview.scrollTo((int)xAxis*100, 100);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
@Override
public void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensor,
SensorManager.SENSOR_DELAY_UI);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
}
布局
<HorizontalScrollView
android:id="@+id/hview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:scaleType="centerCrop"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/img"
android:scaleType="centerCrop"
android:background="#fff"
android:src="@drawable/image" />
</HorizontalScrollView>