利用kotlin的拓展函数和拓展属性轻而易举实现点击事件防重复:
1、新建一个kt文件,复制以下代码:
inline fun <T : View> T.singleClick(time: Long = 800, crossinline block: (T) -> Unit) {
setOnClickListener {
val currentTimeMillis = System.currentTimeMillis()
if (currentTimeMillis - lastClickTime > time || this is Checkable) {
lastClickTime = currentTimeMillis
block(this)
}
}
}
//兼容点击事件设置为this的情况
fun <T : View> T.singleClick(onClickListener: View.OnClickListener, time: Long = 800) {
setOnClickListener {
val currentTimeMillis = System.currentTimeMillis()
if (currentTimeMillis - lastClickTime > time || this is Checkable) {
lastClickTime = currentTimeMillis
onClickListener.onClick(this)
}
}
}
var <T : View> T.lastClickTime: Long
set(value) = setTag(1766613352, value)
get() = getTag(1766613352) as? Long ?: 0
2、使用方法:
tvTest.singleClick(1500) {
Log.e("singClick",System.currentTimeMillis().toString())
}
//括号内为间隔时间,可以忽略,默认800
//或者
tvTest.singleClick {
Log.e("singClick",System.currentTimeMillis().toString())
}
网友评论