传统方式(Java和Kotlin)
private var lastClickTime: Long = 0
view?.setOnClickListener {
if (System.currentTimeMillis() - lastClickTime <= 500L) {
lastClickTime = System.currentTimeMillis()
return@setOnClickListener
}
XXXXX
}
缺点:每次都要写重复代码
RxBinding方式(Java和Kotlin)
依赖RxBinding:
implementation 'com.jakewharton.rxbinding2:rxbinding:2.2.0'
使用:
RxView
.clicks(view!!)
.throttleFirst(500L, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
XXXXX
}
缺点:需要依赖三方库
Kotlin扩展函数+协程(Kotlin)
编写扩展函数:
fun View.setDebounceClickListener(listener: View.OnClickListener, time: Long = 500L) {
var job: Job? = null
this.setOnClickListener {
job?.cancel()
job = CoroutineScope(Dispatchers.Main).launch {
delay(time)
listener.onClick(it)
}
}
}
使用:
view?.setDebounceClickListener(
{
XXXXX
}
)
网友评论