Custom Click Listener to prevent multiple fast clicks

suggest change

In order to prevent a button from firing multiple times within a short period of time (let’s say 2 clicks within 1 second, which may cause serious problems if the flow is not controlled), one can implement a custom SingleClickListener.

This click listener sets a time interval as the threshold (for instance, 1000 ms). When the button is clicked, it checks whether the action already ran inside that interval. If it did, the click is ignored.

public abstract class SingleClickListener implements View.OnClickListener {

    protected int defaultInterval;
    private long lastTimeClicked = 0;

    public SingleClickListener() {
        this(1000);
    }

    public SingleClickListener(int minInterval) {
        this.defaultInterval = minInterval;
    }

    @Override
    public void onClick(View v) {
        if (SystemClock.elapsedRealtime() - lastTimeClicked < defaultInterval) {
            return;
        }
        lastTimeClicked = SystemClock.elapsedRealtime();
        performClick(v);
    }

    public abstract void performClick(View v);

}

Attach it to the button:

myButton = (Button) findViewById(R.id.my_button);
myButton.setOnClickListener(new SingleClickListener() {
    @Override
    public void performClick(View view) {
        // do stuff
    }
});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents