Invoke onClick action with throttle effect

This commit is contained in:
Kirill Nayduik 2021-11-23 11:31:31 +03:00
parent ad29d57377
commit a6107e2e7a
2 changed files with 12 additions and 3 deletions

View File

@ -9,13 +9,15 @@ object ActionThrottler {
// action invoking start user may be in time to click and launch action again
private const val PREVENTION_OF_CLICK_AGAIN_COEFFICIENT = 2
private const val DELAY_MS = PREVENTION_OF_CLICK_AGAIN_COEFFICIENT * RIPPLE_EFFECT_DELAY_MS
const val DEFAULT_THROTTLE_DELAY = 500L
private var lastActionTime = 0L
fun throttleAction(action: () -> Unit): Boolean {
fun throttleAction(throttleDelay: Long = DELAY_MS, action: () -> Unit): Boolean {
val currentTime = SystemClock.elapsedRealtime()
val diff = currentTime - lastActionTime
return if (diff >= DELAY_MS) {
return if (diff >= throttleDelay) {
lastActionTime = currentTime
action.invoke()
true

View File

@ -8,8 +8,13 @@ import android.text.style.URLSpan
import android.text.util.Linkify
import android.view.View
import androidx.annotation.ColorInt
import androidx.core.os.HandlerCompat.postDelayed
import androidx.core.text.HtmlCompat
import ru.touchin.extensions.RIPPLE_EFFECT_DELAY_MS
import ru.touchin.extensions.indexesOf
import ru.touchin.extensions.setOnRippleClickListener
import ru.touchin.utils.ActionThrottler
import ru.touchin.utils.ActionThrottler.DEFAULT_THROTTLE_DELAY
/**
* Convert text with 'href' tags and raw links to spanned text with clickable URLSpan.
@ -66,7 +71,9 @@ fun CharSequence.toClickableSubstringText(
indexesOf(substring)?.let { (startSpan, endSpan) ->
setSpan(object : ClickableSpan() {
override fun onClick(widget: View) {
clickAction.invoke()
ActionThrottler.throttleAction(DEFAULT_THROTTLE_DELAY) {
clickAction.invoke()
}
}
override fun updateDrawState(ds: TextPaint) {