Created
June 3, 2015 02:13
-
-
Save 2BAB/940e4f8633692e681fd4 to your computer and use it in GitHub Desktop.
DebouncedOnClickListener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class DebouncedOnClickListener implements View.OnClickListener { | |
private final long minimumInterval; | |
private Map<View, Long> lastClickMap; | |
/** | |
* setTime | |
* | |
* @param minimumIntervalMsec The minimum allowed time between clicks | |
* - any click sooner than this after a previous click will be rejected | |
*/ | |
public DebouncedOnClickListener(long minimumIntervalMsec) { | |
this.minimumInterval = minimumIntervalMsec; | |
this.lastClickMap = new WeakHashMap<>(); | |
} | |
/** | |
* default | |
*/ | |
public DebouncedOnClickListener() { | |
this(500); | |
} | |
/** | |
* Implement this in your subclass instead of onClick | |
* | |
* @param v The view that was clicked | |
*/ | |
public abstract void onDebouncedClick(View v); | |
@Override | |
public void onClick(View clickedView) { | |
Long previousClickTimestamp = lastClickMap.get(clickedView); | |
long currentTimestamp = SystemClock.uptimeMillis(); | |
lastClickMap.put(clickedView, currentTimestamp); | |
if (previousClickTimestamp == null || (currentTimestamp - previousClickTimestamp > minimumInterval)) { | |
onDebouncedClick(clickedView); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment