Salman Younas Salman Younas - 5 months ago 32
Android Question

Android: Simplest way to calculate delta of touch position?

I want to calculate the delta of touch positions on the screen. For that, I'm using this code:

public boolean onTouchEvent(MotionEvent event) {
touchX = (int) event.getX();
touchY = (int) event.getY();

deltaX = touchX - oldX;
deltaY = touchY - oldY;

oldX = touchX;
oldY = touchY;

return super.onTouchEvent(event);
}


Now, when I move the finger on screen for some time, I get the correct delta. But the problem occurs when I stop my finger, but don't lift it. At that time, I just get the non-zero delta of last frame. It is because
onTouchEvent
is not called when the finger is on screen but static. I should get zero delta when finger is static.

What's the solution to this problem?

Answer

Finger remaining stopped on the screen is not a MotionEvent, so this method will not be called.

Try this.

private Handler mHandler = new Handler();
private static final int FINGER_STOP_THRESHOLD = 500;

public boolean onTouchEvent(MotionEvent event) {
    touchX = (int) event.getX();
    touchY = (int) event.getY();

    deltaX = touchX - oldX;
    deltaY = touchY - oldY;

    oldX = touchX;
    oldY = touchY;

    mHandler.removeCallbacksAndMessages(null);
    if(event.getActionMasked() != MotionEvent.ACTION_UP){
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                deltaX = 0;
                deltaY = 0;
            }
        }, FINGER_STOP_THRESHOLD);
    }

    return super.onTouchEvent(event);
}

You may change the FINGER_STOP_THRESHOLD to the value you want.

Comments