Forked from tieorange/ThrottledOnClickListener.kt
Last active
October 9, 2020 07:30
-
-
Save micadasystems/ce7b9a1cac8bcbba833af7335f7e3bcc to your computer and use it in GitHub Desktop.
A debounced onClickListener for Android
This file contains hidden or 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.westwingnow.android.utils | |
import android.os.SystemClock | |
import android.view.View | |
import java.util.* | |
/** | |
* A Throttled OnClickListener | |
* Rejects clicks that are too close together in time. | |
* This class is safe to use as an OnClickListener for multiple views, and will throttle each one separately. | |
* | |
* * @param minimumIntervalMsec The minimum allowed time between clicks - any click sooner than this after a previous click will be rejected | |
*/ | |
private const val minimumInterval = 1000L | |
class ThrottledOnClickListener(private val onClick: (view: View) -> Unit) : View.OnClickListener { | |
private val lastClickMap: MutableMap<View, Long> = WeakHashMap() | |
override fun onClick(clickedView: View) { | |
val previousClickTimestamp = lastClickMap[clickedView] | |
val currentTimestamp = SystemClock.uptimeMillis() | |
lastClickMap[clickedView] = currentTimestamp | |
if (previousClickTimestamp == null || currentTimestamp - previousClickTimestamp.toLong() > minimumInterval) { | |
onClick.invoke(clickedView) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment