Avoid button multiple rapid clicks

前端 未结 20 1461
猫巷女王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:16

    I use this class together with databinding. Works great.

    /**
     * This class will prevent multiple clicks being dispatched.
     */
    class OneClickListener(private val onClickListener: View.OnClickListener) : View.OnClickListener {
        private var lastTime: Long = 0
    
        override fun onClick(v: View?) {
            val current = System.currentTimeMillis()
            if ((current - lastTime) > 500) {
                onClickListener.onClick(v)
                lastTime = current
            }
        }
    
        companion object {
            @JvmStatic @BindingAdapter("oneClick")
            fun setOnClickListener(theze: View, f: View.OnClickListener?) {
                when (f) {
                    null -> theze.setOnClickListener(null)
                    else -> theze.setOnClickListener(OneClickListener(f))
                }
            }
        }
    }
    

    And my layout looks like this

    
    

提交回复
热议问题