How Kotlin click event to prevent repeat (Android)

Foreword

I believe we in the development work, will often encounter a control is repeated clicks, might cause some unpredictable problems. For example: when a jump activity, click too fast might create two identical interface ~

And everyone to share the next day, use kotlin expansion functions and expand the properties to solve this problem

The first step: create a ids.xml file under res / values directory, defines two attributes:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="triggerDelayKey" type="id"/>
    <item name="triggerLastTimeKey" type="id"/>
</resources>

Step Two: In the project, create a new .kt file, add the following function:

/**
 * get set
 * 给view添加一个上次触发时间的属性(用来屏蔽连击操作)
 */
private var <T : View>T.triggerLastTime: Long
    get() = if (getTag(R.id.triggerLastTimeKey) != null) getTag(R.id.triggerLastTimeKey) as Long else 0
    set(value) {
        setTag(R.id.triggerLastTimeKey, value)
    }

/**
 * get set
 * 给view添加一个延迟的属性(用来屏蔽连击操作)
 */
private var <T : View> T.triggerDelay: Long
    get() = if (getTag(R.id.triggerDelayKey) != null) getTag(R.id.triggerDelayKey) as Long else -1
    set(value) {
        setTag(R.id.triggerDelayKey, value)
    }

/**
 * 判断时间是否满足再次点击的要求(控制点击)
 */
private fun <T : View> T.clickEnable(): Boolean {
    var clickable = false
    val currentClickTime = System.currentTimeMillis()
    if (currentClickTime - triggerLastTime >= triggerDelay) {
        clickable = true
    }
    triggerLastTime = currentClickTime
    return clickable
}

/***
 * 带延迟过滤点击事件的 View 扩展
 * @param delay Long 延迟时间,默认500毫秒
 * @param block: (T) -> Unit 函数
 * @return Unit
 */
fun <T : View> T.clickWithTrigger(delay: Long = 500, block: (T) -> Unit) {
    triggerDelay = delay
    setOnClickListener {
        if (clickEnable()) {
            block(this)
        }
    }
}

Finally: the code used (currently only be called in kotlin code)

        //指定某控件点击间隔时间:1000毫秒
        view.clickWithTrigger (1000){
            ...
        }
        //默认某控件点击间隔时间:500毫秒
        view.clickWithTrigger { 
           ... 
        }

Guess you like

Origin www.cnblogs.com/io1024/p/11597797.html