Fast taps (clicks) on RecyclerView opens multiple Fragments

前端 未结 10 1193
渐次进展
渐次进展 2021-02-02 13:37

I have implemented onClick listener to my ViewHolder for my RecyclerView

But when I perform very fast double taps or mouse clicks, it performs the task (opens a seperate

10条回答
  •  忘掉有多难
    2021-02-02 14:07

    I repurposed the DebouncingOnClickListener from Butterknife to debounce clicks within a specified time, in addition to preventing clicks on multiple views.

    To use, extend it and implement doOnClick.

    DebouncingOnClickListener.kt

    import android.view.View
    
    /**
     * A [click listener][View.OnClickListener] that debounces multiple clicks posted in the
     * same frame and within a time frame. A click on one view disables all view for that frame and time
     * span.
     */
    abstract class DebouncingOnClickListener : View.OnClickListener {
    
        final override fun onClick(v: View) {
            if (enabled && debounced) {
                enabled = false
                lastClickTime = System.currentTimeMillis()
                v.post(ENABLE_AGAIN)
                doClick(v)
            }
        }
    
        abstract fun doClick(v: View)
    
        companion object {
            private const val DEBOUNCE_TIME_MS: Long = 1000
    
            private var lastClickTime = 0L // initially zero so first click isn't debounced
    
            internal var enabled = true
            internal val debounced: Boolean
                get() = System.currentTimeMillis() - lastClickTime > DEBOUNCE_TIME_MS
    
            private val ENABLE_AGAIN = { enabled = true }
        }
    }
    

提交回复
热议问题