Abdalrahman Shatou
Abdalrahman Shatou

Reputation: 4748

Android - Receiving wrong touch events

Here is the code I am using:

// Handling Touch Events
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {

    float onOffBitmapWidth = this.onOffBitmap.getWidth();
    if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

        if (this.touchMove) {
            if (togglePositionX > this.onOffBitmap.getWidth() / 4.0f) {
                togglePositionX = this.onOffBitmap.getWidth() / 2.0f - this.toggleBitmap.getWidth()/4.0f;
            } else if (togglePositionX <= this.onOffBitmap.getWidth() / 4.0f) {
                togglePositionX = 0.0f;
            }

            this.invalidate();
            this.touchMove = false;
            return true;

        } else {

            return false;

        }

    } else if (motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {

        this.touchMove = false;
        this.invalidate();

    } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {

        this.touchMove = true;

        float currentX = motionEvent.getX();

        if (currentX > 0.0f && currentX < (this.onOffBitmap.getWidth() / 2.0f - this.toggleBitmap.getWidth()/4.0f)) {
            togglePositionX = currentX;
        } else if (currentX >= (this.onOffBitmap.getWidth() / 2.0f - this.toggleBitmap.getWidth()/4.0f)) {
            togglePositionX = this.onOffBitmap.getWidth() / 2.0f - this.toggleBitmap.getWidth()/4.0f;
        } else if (currentX <= 0.0f) {
            togglePositionX = 0.0f;
        }

        this.invalidate();
        return true;

    }

    return true;

}

@Override
public void onClick(View v) {

    if (togglePositionX == 0.0f) {
        togglePositionX = this.onOffBitmap.getWidth() / 2.0f - this.toggleBitmap.getWidth()/4.0f;
    } else {
        togglePositionX = 0.0f;
    }

    this.invalidate();

}

I am using onClick event for single tap event. The problem is that ACTION_MOVE is called even if I only tap the screen. I even do it in a funny way (with the very tip of my finger).

Upvotes: 0

Views: 287

Answers (1)

Abdalrahman Shatou
Abdalrahman Shatou

Reputation: 4748

I end up using an array list containing the history of touch positions that the user performs on the view + a flag to detect wether it's a real ACTION_MOVE or not. Here is the code that I implemented inside if (motionEvent.getAction() == MotionEvent.ACTION_MOVE)

float currentX = motionEvent.getX();
        this.userTouchMoveArray.add(currentX);

        if (this.userTouchMoveArray.size() == 1) {
            touchIsMoved = false;
        } else {
            float oldestX = userTouchMoveArray.get(0);
            if (Math.abs(currentX - oldestX) > 2.0f) {
                touchIsMoved = true;
            } else {
                touchIsMoved = false;
            }
        }

Working like a charm. (You can define your own tolerance, here I am using 2 px)

Upvotes: 1

Related Questions