在 Android 中使用加速度计时 ImageView 图像超出屏幕

问题描述

这是我的 Java 代码 我只是想让 ImageView 图像限制到屏幕边界或停止走出屏幕...... ScreenShort is Showing the output while using the application

包com.example.javagame;

公共类 MainActivity 扩展 AppCompatActivity 实现 SensorEventListener {

private SensorManager sensorManager;
private Sensor accelerometer;
private long lastUpdate;

ImageView mDrawable;
public static int x = 0;
public static int y = 0;
public static int z = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mDrawable = (ImageView) findViewById(R.id.checkPic);
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    lastUpdate = System.currentTimeMillis();


    int mWidth = this.getResources().getdisplayMetrics().widthPixels;
    int mHeight = this.getResources().getdisplayMetrics().heightPixels;

    Log.e("centreX","" + mWidth);
    Log.e("centreY","" + mHeight);
    mDrawable.setPivotX(100);
    mDrawable.setPivotY(100);

}
@Override
protected void onResume() {
    super.onResume();
    sensorManager.registerListener(this,accelerometer,SensorManager.SENSOR_DELAY_GAME);
}

@Override
protected void onPause() {
    super.onPause();
    sensorManager.unregisterListener(this);
}




@Override
public void onSensorChanged(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

        x -= (int) event.values[0];
        y += (int) event.values[1];



        mDrawable.setY(y);
        mDrawable.setX(x);

    }
}

@Override
public void onAccuracyChanged(Sensor sensor,int accuracy) {

}

}

When Program Start

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)