Android 两种方式优雅实现按钮防重复点击,防抖功能

1. Kotlin 扩展函数实现防抖(Kotlin)

1.1创建ViewExtension.kt文件:

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
}

}

1.2 如何调用

只要是继承View的控件 即可实现view.clickWithTrigger调用(仅限kotlin)

// 例:
Button mBtn = findViewByid(R.id.btn)
mBtn.clickWithTrigger{
     
    // 业务逻辑
}

2.RxBinding实现防抖(Java)

2.1 添加依赖

implementation "com.jakewharton.rxbinding3:rxbinding:3.0.0"

2.2 如何实现

// 例:
RxView.clicks(view)
	  .throttleFirst(1000L,TimeUnit.MILLISECONDS) // 1秒内只有第一次点击有效
      .observeOn(AndroidSchedulers.mainThread())  
      .subscribe(x -> {
      // 业务逻辑
      });

你可能感兴趣的:(Android,移动开发,android,java)