Search code examples
androidonclickonclicklistenergesturedouble-click

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!


Solution

  • 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();
    }