Mallika Mallika - 3 months ago 21
Android Question

How to prevent rapid double click on a button

I have looked at the answers here - Android Preventing Double Click On A Button
and implemented qezt's solution like and I've tried

setEnabled(false)
like so -

doneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

// mis-clicking prevention, using threshold of 1 second
if (SystemClock.elapsedRealtime() - doneButtonClickTime < 1000){
return;
}

//store time of button click
doneButtonClickTime = SystemClock.elapsedRealtime();

doneButton.setEnabled(false);

//do actual work

}
});


Neither of these work against super fast double clicks.

Note - I'm not setting
doneButton.setEnabled(true)
after my processing is done. I simply finish() the activity so there is no issue of the button getting enabled too soon.

Answer

I am doing like this it works very well.

public abstract class OnOneOffClickListener implements View.OnClickListener {

   private static final long MIN_CLICK_INTERVAL=600;

   private long mLastClickTime;

   public static boolean isViewClicked = false;


   public abstract void onSingleClick(View v);

   @Override
   public final void onClick(View v) {
       long currentClickTime=SystemClock.uptimeMillis();
       long elapsedTime=currentClickTime-mLastClickTime;

       mLastClickTime=currentClickTime;

       if(elapsedTime<=MIN_CLICK_INTERVAL)
           return;
       if(!isViewClicked){
           isViewClicked = true;
           startTimer();
       } else {
           return;
       }
       onSingleClick(v);        
   }
    /**
     * This method delays simultaneous touch events of multiple views.
     */
    private void startTimer() {
        Handler handler = new Handler();

        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                    isViewClicked = false;
            }
        }, 600);

    }

}
Comments