logicalfox
logicalfox

Reputation: 83

Getting distance between android ACTION_DOWN and ACTION_UP events

I want to get the distance between the point where a user presses the screen (ACTION_DOWN) and where they release it (ACTION_UP). This is to be able to move the bitmap image the same amount (even if it gets pushed off-screen) without causing it to jump back to the cursor position (or back on-screen). However my code seems to move the image the wrong direction sometimes, or cause it to keep moving even when I release the screen press. Is there a debounce issue here that I need to account for?

My onTouch method (get ACTION_DOWN point and ACTION_UP point, and subtract one from other)

public boolean onTouch(View v, MotionEvent event) {
    int action = event.getAction();
    if(action == event.ACTION_DOWN) {
    preFingerPosX = event.getX();
        preFingerPosY = event.getY();
    }
    else if(action == event.ACTION_UP) {
        fingerPosX = event.getX();
        fingerPosY = event.getY();
    }
    dx = fingerPosX - preFingerPosX;
    dy = fingerPosY - preFingerPosY;
    bmpX += dx;
    bmpY += dy;

    //invalidate();        
    return true;
}

And my run() method

public void run() {
        // TODO Auto-generated method stub
        while(isRunning) {
            if(!surfaceHolder.getSurface().isValid()) {
                continue;
            }


            canvas = surfaceHolder.lockCanvas();

            canvas.drawRGB(0, 0, 0);
            canvas.drawBitmap(bmp, bmpX-(bmp.getWidth()/2),
                                        bmpY-(bmp.getHeight()/2), null);
            surfaceHolder.unlockCanvasAndPost(canvas);

        }
}

Thanks

Upvotes: 0

Views: 1449

Answers (1)

Trevor
Trevor

Reputation: 10993

In your onTouch() handler, you're still executing this bit:

dx = fingerPosX - preFingerPosX;
dy = fingerPosY - preFingerPosY;
bmpX += dx;
bmpY += dy;

even if the event isn't ACTION_DOWN or ACTION_UP.

Therefore, bmpX and bmpY are being incremented / decremented by dx/dy potentially hundreds of times between the ACTION_DOWN and the ACTION_UP, due to the (potentially hundreds of) ACTION_DOWN events (and possibly other events too) that happen between the initial down and final up events.

Also, usually you would want your object to actually track the finger process during the gesture, so you might want to have a specific handler for ACTION_DOWN.

Upvotes: 1

Related Questions