Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override onClick listener of all view in my android application?

On activity A I have a button named btnA which will show an activity B whenever it is clicked.

But if I click on this btnA button too fast like 2 clicks within a second then 2 activity B will be shown. Obviously.

I know the solution for this is debouncing the on click listener of btnA using RxBinding or Kotlin coroutine...

But what if a have 100 views which all behave just like btnA in my app. How can I somehow override or intercept their on click listener to apply debouncing in one place?

Edit: I'm using Kotlin which mean I can add an extension function to apply the debounce logic over View's on click listener but that won't work if the click event handler is bound by ButterKnife or other alternatives library. That why I'm finding a way to override or intercept the View's click listener.

Also, creating some sort of root View/ base View which all app's View will extend from might be overkill, I think.

This might be impossible at the moment but somehow I have an urge that there is a solution somewhere out there.

like image 851
Harvey Avatar asked Aug 31 '25 01:08

Harvey


1 Answers

I do not know of any way to globally override all click listeners. Likely, this is not possible. But if you use Kotlin, you could do something like this:

fun View.onClickThrottled(skipDurationMillis: Long = 750, action: () -> Unit) {
  var isEnabled = true
  this.setOnClickListener {
    if (isEnabled) {
      action()
      isEnabled = false
      Handler().postDelayed({ isEnabled = true }, skipDurationMillis)
    }
  }
}

And then, change your views to use this instead, like this:

button.onClickThrottled {
   //TODO - do something
}
like image 121
EAlgekrans Avatar answered Sep 02 '25 16:09

EAlgekrans