adapter的点击事件
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
abstract class ABCClickListener : OnItemClickListener {
private var lastClickTime = 1L
abstract fun onThrottleFirstClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int)
override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
val currentTimeMillis = System.currentTimeMillis()
if ((currentTimeMillis - lastClickTime) >= 1000) {
lastClickTime = currentTimeMillis
onThrottleFirstClick(adapter, view, position)
}
}
}
view的点击事件 协程
fun View.setDebounceClickListener(l: View.OnClickListener) {
var job: Job? = null
this.setOnClickListener {
job?.cancel()
job = CoroutineScope(Dispatchers.Main).launch {
delay(250)
l.onClick(it)
}
}
}
扩展函数实现
package com.a.b.utils
import android.view.View
fun <T : View> T.withTrigger(delay: Long = 800): T {
triggerDelay = delay
return this
}
/***
* 点击事件的View扩展
* @param block: (T) -> Unit 函数
* @return Unit
*/
fun <T : View> T.click(block: (T) -> Unit) = setOnClickListener {
// ClickUtils.applyPressedViewAlpha(this,0.8f)
if (clickEnable()) {
block(it as T)
}
}
/***
* 带延迟过滤的点击事件View扩展
* @param delay Long 延迟时间,默认800毫秒
* @param block: (T) -> Unit 函数
* @return Unit
*/
fun <T : View> T.clickWithTrigger(time: Long = 800, block: (T) -> Unit) {
// 此处是点击后按钮背景透明度变化 可参考blankj开源工具类
// ClickUtils.applyPressedViewAlpha(this,0.6f)
triggerDelay = time
setOnClickListener {
if (clickEnable()) {
block(it as T)
}
}
}
private var <T : View> T.triggerLastTime: Long
get() = if (getTag(1123460103) != null) getTag(1123460103) as Long else 0
set(value) {
setTag(1123460103, value)
}
private var <T : View> T.triggerDelay: Long
get() = if (getTag(1123461123) != null) getTag(1123461123) as Long else -1
set(value) {
setTag(1123461123, value)
}
private fun <T : View> T.clickEnable(): Boolean {
var flag = false
val currentClickTime = System.currentTimeMillis()
if (currentClickTime - triggerLastTime >= triggerDelay) {
flag = true
}
triggerLastTime = currentClickTime
return flag
}