Sample code for continuous clicking of android mask button

  • 2021-12-11 08:47:39
  • OfStack

In the development of android, there will inevitably be many buttons clicked. In order to prevent users from deliberately clicking buttons continuously, resulting in too many unnecessary requests in a short time, or the problem of multiple page jumps, the client needs to shield the clicking actions, that is, shield the continuous clicking in a short time. (Of course, this is only to minimize the occurrence of the above problems. If the hand speed is fast enough, it will still appear.)

Correct code:


abstract class OnMultiClickListener(private val interval: Long = MULTI_CLICK_INTERVAL): View.OnClickListener {
  private companion object {
    private const val MULTI_CLICK_INTERVAL = 500L
  }
 
  private var mLastClickTime = 0L
 
  abstract fun onMultiClick(v: View?)
 
  final override fun onClick(v: View?) {
    v.runSafety {
      val currentTime = System.currentTimeMillis()
      // Note that absolute values are used here 
      if (abs(currentTime - mLastClickTime) < interval) {
        mLastClickTime = currentTime // Assignment 1
        return
      }
  
      mLastClickTime = currentTime // Assignment 2
 
      onMultiClick(v)
 
    }
  }
}

Note:

1. If the interval time is set too long, it may cause the phenomenon of clicking on stuck visually

2. If the system time is modified, it may cause a problem in judging the time, which will lead to no response when the button is clicked. Therefore, absolute values must be used for comparison.

3. Pay attention to the two assignment positions


Related articles: