Custom Click Listener to prevent multiple fast clicks
suggest changeIn 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 ClickListener sets a specific time interval as threshold (for instance, 1000ms). When the button is clicked, a check will be ran to see if the trigger was executed in the past amount of time you defined, and if not it will trigger it.
public 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);
}
And in the class, the SingleClickListener is associated to the Button at stake
myButton = (Button) findViewById(R.id.my_button);
myButton.setOnClickListener(new SingleClickListener() {
@Override
public void performClick(View view) {
// do stuff
}
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents