Created
September 18, 2018 07:52
-
-
Save truefedex/3802c950e6c77a6050433a2481091db5 to your computer and use it in GitHub Desktop.
Simple solution for classic "debouncing" problem (ability of user to click simultaneously on several UI elements or fast clicking on one element with asynchronous result )
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
package com.example; | |
import android.support.annotation.NonNull; | |
import android.view.View; | |
/** | |
* Simple solution for classic "debouncing" problem (ability of user to click simultaneously | |
* on several UI elements or fast clicking on one element with asynchronous result ) | |
*/ | |
public abstract class DebouncedClickListener implements View.OnClickListener{ | |
public static final int DEFAULT_MIN_CLICK_INTERVAL_MS = 750; | |
private static ClickLock clickLockGlobal = new ClickLock(DEFAULT_MIN_CLICK_INTERVAL_MS, true); | |
public ClickLock clickLock; | |
public static class ClickLock { | |
private final int minClickIntervalMs; | |
private final boolean autoUnlock; | |
public long lastClickTime; | |
public boolean lockedState = false; | |
public ClickLock(int minClickIntervalMs, boolean autoUnlock) { | |
this.minClickIntervalMs = minClickIntervalMs; | |
this.autoUnlock = autoUnlock; | |
} | |
} | |
public DebouncedClickListener(@NonNull ClickLock clickLock) { | |
this.clickLock = clickLock; | |
} | |
public DebouncedClickListener() { | |
this(clickLockGlobal); | |
} | |
@Override | |
public void onClick(View v) { | |
if (clickLock.lockedState && !clickLock.autoUnlock) { | |
return;//only manually unlock is possible | |
} | |
long now = System.currentTimeMillis(); | |
if ((now - clickLock.lastClickTime) < clickLock.minClickIntervalMs) { | |
return; | |
} | |
clickLock.lastClickTime = now; | |
clickLock.lockedState = true; | |
onClickDebounced(v); | |
} | |
public abstract void onClickDebounced(View v); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment