我正在显示一张全景照片,并且我希望我的 ImageView 根据传感器方向移动(我手机的方向决定了图像视图,并且它太宽而无法一次完全显示)。当我调用改变我的 ImageView 的方法(例如 setX)时,我的应用程序崩溃了。我是在 UI 线程中做的,所以我不知道为什么这不起作用。引用传感器的代码工作正常。
任何帮助,将不胜感激。
public class ImageActivity extends Activity
{
private ImageView imageView;
private LocationManager locationManager;
private String provider;
private SensorManager sensorManager;
public float val = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
sensorManager.registerListener(new CustomOrientationListener(), sensor,
SensorManager.SENSOR_DELAY_GAME);
//imageView = (ImageView) findViewById(R.id.imageView1);
}
class CustomOrientationListener implements SensorEventListener {
public CustomOrientationListener() {}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
@Override
public void onSensorChanged(SensorEvent event) {
final float[] values;
if(event.sensor.getType() == Sensor.TYPE_ORIENTATION){
values = event.values;
runOnUiThread(new Runnable(){
@Override
public void run() {
imageView.setTranslationX((int)values[0]);
}
});
}
}
}
}