Avoid button multiple rapid clicks

前端 未结 20 1457
猫巷女王i
猫巷女王i 2020-11-28 02:55

I have a problem with my app that if the user clicks the button multiple times quickly, then multiple events are generated before even my dialog holding the button disappear

20条回答
  •  攒了一身酷
    2020-11-28 03:04

    We can do it without any library. Just create one single extension function:

    fun View.clickWithDebounce(debounceTime: Long = 600L, action: () -> Unit) {
        this.setOnClickListener(object : View.OnClickListener {
            private var lastClickTime: Long = 0
    
            override fun onClick(v: View) {
                if (SystemClock.elapsedRealtime() - lastClickTime < debounceTime) return
                else action()
    
                lastClickTime = SystemClock.elapsedRealtime()
            }
        })
    }
    

    View onClick using below code:

    buttonShare.clickWithDebounce { 
       // Do anything you want
    }
    

提交回复
热议问题