package fr.cyu.td7; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; public class MySurfaceView extends SurfaceView implements Runnable, View.OnTouchListener { private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); private Thread thread = null; private SurfaceHolder sh; private boolean paused = true; private boolean dragging; private int x; private int y; public MySurfaceView(Context context, AttributeSet attrSet) { super(context, attrSet); sh = getHolder(); setOnTouchListener(this); x = getWidth() / 2; y = getHeight() / 2; } @Override public boolean onTouch(View v, MotionEvent event) { int x = (int) event.getX(); // pixel coordinates int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: int size = getWidth() / 4; boolean inX = x >= this.x - size && x <= this.x + size; boolean inY = y >= this.y - size && y <= this.y + size; Log.i("fr.cyu.td7", "Down: x=" + x + ", y=" + y + ", maxX=" + (this.x + getWidth() / 4) + ", maxY=" + (this.y + getWidth() / 4) + ", this.x=" + this.x + ", this.y=" + this.y + ", inX=" + inX + ", inY=" + inY); if (inX && inY) dragging = true; break; case MotionEvent.ACTION_UP: dragging = false; break; case MotionEvent.ACTION_MOVE: if(dragging) { this.x = x; this.y = y; } break; } return true; // the event has been consumed } public void resume() { // to call in Activity.onResume paused = false; thread = new Thread(this); thread.start(); } public void pause() {// to call in Activity.onPause paused = true; while (true) { try { thread.join(); break; } catch (InterruptedException e) { Log.e("fr.cyu.td7", "Error when pausing", e); } } thread = null; } public void run() { while (!paused) { if (!sh.getSurface().isValid()) continue; Canvas canvas = sh.lockCanvas(); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); paint.setColor(Color.GREEN); canvas.drawPaint(paint); paint.setColor(Color.WHITE); int size = dragging ? getWidth() / 5 : getWidth() / 4; canvas.drawCircle(x, y, size, paint); sh.unlockCanvasAndPost(canvas); } } }