3

我是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();

    }

}
}

感谢您的帮助:) 尊重

4

1 回答 1

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;
}
于 2013-07-09T16:40:06.043 回答