Home > other >  Is there more effective way to prevent multiple click event in Android
Is there more effective way to prevent multiple click event in Android

Time:12-24

When the user taps the button multiple times in a short period, then multiple events are being called. As an example, we have a button called 'view cart', and when the user clicks it, 'Cart screen' will be opened. The issue is, if the user clicks 'view cart' button multiple times, 'Cart screen' will be opened multiple times. Below are codes of solution I have found.

// variable to  prevent double tapping 
private var lastClickTime: Long = 0

... ...
viewDataBinding?.layoutViewCart?.setOnClickListener {
    openCart()
}

// Open Cart page
private fun openCart() {
   if (SystemClock.elapsedRealtime() - lastClickTime > 500) {
     lastClickTime = SystemClock.elapsedRealtime()
     ... ... ...
  }
}

But it's not good to write this code for all components, all clickedListeners. Do we have better solution?

CodePudding user response:

You made it 90% there. You can abstract that last click timer into its own class that wraps an actual onClickListner. And when you implement it you override the wrapper and then you wont have to keep making the same logic over and over again. Here is a example in Java but should be easily convertible.

How to prevent rapid double click on a button

  • Related