Reputation: 10552
Im trying to draw a square on a canvas
but only the MotionEvent.ACTION_DOWN
is run, and then the listener
stops.
The idea is when the user touches the screen it get the x1 and y1 locations and every time the onTouch
is fired it must draw the rect frim x1 y1 to the current location, and lastly save the last location in x2 y2 once the user lets go of the screen.
My code looks like this:
surfaceView.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
holder = surfaceView.getHolder();
canvas = holder.lockCanvas();
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
x1=event.getX();
y1=event.getY();
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
x2=event.getX();
y2=event.getY();
}
canvas.drawRect(x1, y1, event.getX(), event.getY(), paint);
holder.unlockCanvasAndPost(canvas);
return true;
}
});
Can anyone give me an example.
Upvotes: 0
Views: 178
Reputation: 1140
ACTION_UP triggers from above code. Try the code below and you will see the log.
I think your problem may be related with the points you get. I don't know how you defined x1, y1, x2, y2 but when declared out of scope they must be final. Try this instead.
final SurfaceView s = (SurfaceView) findViewById(R.id.surface);
final RectF rect = new RectF();
s.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
SurfaceHolder holder = s.getHolder();
Canvas canvas = holder.lockCanvas();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
Log.d("action", "down");
rect.left = event.getX();
rect.top = event.getY();
}
if(event.getAction() == MotionEvent.ACTION_UP){
Log.d("action", "up");
rect.right = event.getX();
rect.bottom = event.getY();
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawRect(rect, paint);
}
holder.unlockCanvasAndPost(canvas);
return true;
}
});
Upvotes: 1
Reputation: 4007
Try using this.
surfaceView.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
x1=event.getX();
y1=event.getY();
}
else if(event.getAction() == MotionEvent.ACTION_UP)
{
x2=event.getX();
y2=event.getY();
holder = surfaceView.getHolder();
canvas = holder.lockCanvas();
canvas.drawRect(x1, y1, x2, y2, paint);
holder.unlockCanvasAndPost(canvas);
}
return true;
}
});
If you move your finger it calls the listener every move you do. So this code
holder = surfaceView.getHolder();
canvas = holder.lockCanvas();
and this code
canvas.drawRect(x1, y1, event.getX(), event.getY(), paint);
holder.unlockCanvasAndPost(canvas);
Will be executed, maybe that's why it's stopping.
So I put the drawRect
inside the MotionEvent.ACTION_UP
condition, so the drawRect
will be executed once.
Upvotes: 0