0

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?

  • How do you actually open the cart screen? Are you using the Navigation Component? Fragments directly? Or something else? – ianhanniballake Dec 23 '21 at 17:50
  • The problem is not just opening cart screen. It's just an example. My goal is to build a component system to prevent user's multiple click by mistake or something else. – Kevin Cloud Dec 23 '21 at 17:52
  • If the `DialogFragment` doesn't instantly popup the user can certainly press it multiple times and result in multiple of the same `DialogFragment` being created and displayed on top of one either. Harder to pull off on newer device but it can happen. – avalerio Dec 23 '21 at 17:56
  • The way to handle this properly without random timeouts differs based on what you are doing. – ianhanniballake Dec 23 '21 at 17:56

1 Answers1

0

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

avalerio
  • 2,072
  • 1
  • 12
  • 11