DataBinding防止多次点击 DataBinding防误触 DataBinding点击防抖
程序员文章站
2022-03-31 08:22:18
点击事件防多次点击的方法有很多种,比如使用rxjava,自己写防抖事件等等,由于业务需要,我使用的是协程+livedata+Lifecycle实现首先是防误触处理//点击事件防抖@OptIn(ExperimentalCoroutinesApi::class)@CheckResultfun View.singleClick(duration:Long = 600) = callbackFlow { var lastClick = 0L val liste...
点击事件防多次点击的方法有很多种,比如使用rxjava,自己写防抖事件等等,由于业务需要,我使用的是协程+livedata+Lifecycle实现
首先是防误触处理
//点击事件防抖
@OptIn(ExperimentalCoroutinesApi::class)
@CheckResult
fun View.singleClick(duration:Long = 600) = callbackFlow<View> {
var lastClick = 0L
val listener = View.OnClickListener {
if(System.currentTimeMillis() - lastClick > duration){
kotlin.runCatching { offer(it) }
lastClick = System.currentTimeMillis()
}
}
setOnClickListener(listener)
awaitClose { setOnClickListener(null) }
}
@OptIn(ExperimentalCoroutinesApi::class)
fun View.singleClick(owner: LifecycleOwner, duration:Long = 600, observer: Observer<View>) =
singleClick(duration)
.asLiveData()
.observe(owner,observer)
然后是把事件和databinding绑定
@BindingAdapter("singleClick",requireAll = false)
fun setSingleClick(view: View, listener:View.OnClickListener?){
val owner = ViewTreeLifecycleOwner.get(view)
if(listener != null && owner != null){
view.singleClick(owner){
listener.onClick(it)
}
}
}
接下来写事件方法
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="防多次点击测试"
android:textColor="@color/colorPrimary"
android:gravity="center"
singleClick="@{()->vm.click1()}" />
/data里写事件方法
class ClickViewModel :BaseViewModel(){
//方法名可以随便起
fun click1(){
LogUtils.e("点击了按钮")
}
}
本文地址:https://blog.csdn.net/jingzz1/article/details/109380475