Last active
June 21, 2019 01:55
-
-
Save samehmikhail/d9597b5bdebf9a01122b3abfd05b6f42 to your computer and use it in GitHub Desktop.
Android kotlin view extension that adds protection period that prevent firing onClick event within defined window. Which is helping to filter click events that may come from monkey testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.view.View | |
fun View.setOnClickListener2(listener : View.OnClickListener) { | |
setOnClickListener(ClickListenerWrapper(listener)) | |
} | |
fun View.setOnClickListener2(listener : (v: View)->Unit) { | |
setOnClickListener(ClickListenerWrapper(listener)) | |
} | |
private class ClickListenerWrapper : View.OnClickListener { | |
private val listener1 : View.OnClickListener? | |
private val listener2 : ((v: View)->Unit)? | |
private var lastClickTimestamp : Long = 0 | |
constructor(listener : View.OnClickListener){ | |
this.listener1 = listener | |
this.listener2 = null | |
} | |
constructor(listener : (v: View)->Unit){ | |
this.listener1 = null | |
this.listener2 = listener | |
} | |
override fun onClick(v: View) { | |
val timestamp = System.currentTimeMillis() | |
if (canConsumeClickAt(timestamp)) { | |
listener1?.onClick(v) | |
listener2?.invoke(v) | |
lastClickTimestamp = timestamp | |
} | |
} | |
private fun canConsumeClickAt(timestamp: Long): Boolean = (timestamp - lastClickTimestamp) >= EVENT_CONSUMPTION_WINDOW | |
companion object { | |
private val EVENT_CONSUMPTION_WINDOW = 1000L | |
private val TAG = ClickListenerWrapper::class.java.simpleName | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment