HeyThere
HeyThere

Reputation: 583

Android avoid calling single tap twice for double tap, without using onSingleTapConfirmed

My app has a View which is clickable, and then when this View is clicked, a handleClickEvent() should be called. I tried setting an OnClickListener to the view, but then when user is double tapping the view, the handleClickEvent() gets called twice. I don't want it to be called twice during double tap. I.e. I want handleClickEvent() be called ONCE for both single click and double tap.

I did some research and found out this question: Android detecting double tap without single tap first I tried what's suggested in the answer, i.e. implementing a GestureDetector with onSingleTapConfirmed() method. That worked, however I notice that there is a noticeable delay on the response time, comparing to using OnClickListener. I assume it is because onSingleTapConfirmed() is called only after the system confirms that this is a single tap by waiting for some certain time period.

Is there anyway to achieve this without having a noticeable delay? Another option I can think of is to have a lastClickedTimeStamp member variable, compare the current time when clicked with lastClickedTimeStamp, and if it is within some threshold don't do anything.

I am wondering if there are any other options?

Thank you!

Upvotes: 1

Views: 1604

Answers (2)

Amad Yus
Amad Yus

Reputation: 2866

You can try using GestureDetector.SimpleOnGestureListener and combine it with onTouchEvent.

private GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        Log.d("SingleTap", " is detected");
        return true;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        Log.d("DoubleTap", " is detected");
        return true;
    }
});

then, remove onClickListener and set touch event on that view

 yourView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        return gestureDetector.onTouchEvent(event);
    }
});

You can refer to Detecting Common Gestures

Upvotes: 0

Cameron Monks
Cameron Monks

Reputation: 117

The way I would do it is set a state variable as a long and call it timeOfLastTouch and set it to 0. Then in each OnClickListener function put this code in their

long currentTime = System.currentTimeMillis();
if (timeOfLastTouch + 100 < currentTime) {
    // code
    timeOfLastTouch = System.currentTimeMillis();
}

Upvotes: 2

Related Questions