Skip to content

Instantly share code, notes, and snippets.

@SINGHPRT
Created September 4, 2017 06:30
Show Gist options
  • Select an option

  • Save SINGHPRT/9f4d26477e6b5da0a6f1eb8c5dd752cb to your computer and use it in GitHub Desktop.

Select an option

Save SINGHPRT/9f4d26477e6b5da0a6f1eb8c5dd752cb to your computer and use it in GitHub Desktop.
What is Event Debouncing:
==========================
There are several situations in UI event paradigm where you want
control to limit/bound an event to fire only once after a specific amount of time has passed or within a given time-interval.
Event listeners bound to the keyup in search boxes, screen resize and scroll events are the typical candidates for debouncing in JAVASCRIPT.
Android has similar issues found with button click.
How to debounce an Button Click event in Android:
====================================================
1. Extend Click Listener with timer to track click events
2. Allow calling of click logic
Custom Click Listener Class
=============================
import android.os.SystemClock;
import android.view.View;
/**
* Created by singhprt on 04-09-2017.
*/
public abstract class DebouncedClickListener implements View.OnClickListener {
protected int defaultInterval;//override in child class
private long lastTimeClicked = 0;
public DebouncedClickListener() {
this(1000);//Default 1 second interval
}
public DebouncedClickListener(int minInterval) {
this.defaultInterval = minInterval;
}
@Override
public void onClick(View v) {
if ((SystemClock.elapsedRealtime() - lastTimeClicked) < defaultInterval) {
return;
}
lastTimeClicked = SystemClock.elapsedRealtime();
performClick(v);
}
//This is the method to call on click, must implement at child class
public abstract void performClick(View v);
}
Binding Debouncer to Button
============================
//Limiting clicks to one click per Second
btnOrderFood.setOnClickListener(new DebouncedClickListener() {
@Override
public void performClick(View v) {
orderFood();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment