如何用加速度计传感器移动圆圈?

时间:2013-07-09 16:09:44

标签: android accelerometer

我是android编程的初学者。我想编写一个应该用加速度传感器改变圆的位置的程序。我的代码在下面,圆圈的位置被改变但是圆圈没有移动到屏幕的右边或下面,圆圈移动了一点:(即使我移动了太多的手机。 我的问题:如何用加速度计传感器将球(圆圈)移动到屏幕的下方或右侧?

public class MainActivity extends Activity implements SensorEventListener{

ShapeDrawable shapeDrawable=new ShapeDrawable();
public static int x;
public static int y;
public static Object bimtap;
Bitmap bitmap;

private SensorManager sm;

CustomDrawableView cDraw;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    sm=(SensorManager)getSystemService(SENSOR_SERVICE);
    cDraw=new CustomDrawableView(this);
    setContentView(cDraw);
}

public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub

}

public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
        //
        x=(int)Math.pow(event.values[0], 2);
        y=(int)Math.pow(event.values[1], 2);
    }
}

@Override
public void onResume(){
    super.onResume();
    sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
public void onStop(){
    sm.unregisterListener(this);
    super.onStop();
}

public class CustomDrawableView extends View{

    int width=150;
    int height=150;

    public CustomDrawableView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        shapeDrawable=new ShapeDrawable();
    }

    public void onDraw(Canvas canvas){
        Paint paint=new Paint();
        paint.setColor(Color.BLUE);
        canvas.drawCircle(MainActivity.x+50, MainActivity.y+50, 25, paint);
        invalidate();

    }

}
}

感谢您的帮助:) 方面

1 个答案:

答案 0 :(得分:0)

以下代码移动您点击的圈子

public class Custom_View extends View {
private PointF point;
private Paint paint;

public Custom_View(Context context) {
    this(context, null);
}

public Custom_View(Context context, AttributeSet attrs) {
    super(context, attrs);
    paint = new Paint(Paint.ANTI_ALIAS_FLAG);
}

@Override
protected void onDraw(Canvas canvas) {
    if (point != null) {
        int radius = 50;
            paint.setColor(Color.GREEN);
            canvas.drawCircle(point.x, point.y, radius, paint);
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        point = new PointF(event.getX(), event.getY());
        break;
    case MotionEvent.ACTION_UP:
        point = null;
        break;
    case MotionEvent.ACTION_MOVE:
        point = new PointF(event.getX(), event.getY());
        break;
    }
    invalidate();
    return true;
}