android防止连续点击的简单实现(kotlin)

首先 方法类:

package com.zhou.base.utils

/**
 * Created by zhou on 17/3/20.
 */
object ToolsUtil {
    //防止连续点击
    /** 判断是否是快速点击  */
    private var lastClickTime: Long = 0
    val isFastDoubleClick: Boolean
        get() {
            val time = System.currentTimeMillis()
            val timeD = time - lastClickTime
            if (timeD < 500) {
                return true
            }
            lastClickTime = time
            return false
        }
}

代码很容易理解,就是计算点击的时间差,从而控制可点击的频率。

创建两个类:
NoDoubleClickListener.kt

package com.zhou.base.listener

import android.view.View
import com.zhou.base.utils.ToolsUtil

/**
 * Created by zhou on 16/12/14.
 */
abstract class NoDoubleClickListener : View.OnClickListener {
    override fun onClick(v: View) {
        if (ToolsUtil.isFastDoubleClick) {
            return
        }
        onNoDoubleClick(v)
    }

    abstract fun onNoDoubleClick(v: View?)
}

NoDoubleOnItemClickListener.kt

package com.zhou.base.listener

import android.view.View
import android.widget.AdapterView
import com.zhou.base.utils.ToolsUtil

/**
 * Created by zhouruiyong on 16/12/14.
 */
abstract class NoDoubleOnItemClickListener : AdapterView.OnItemClickListener {
    override fun onItemClick(
        adapterView: AdapterView<*>?,
        view: View,
        position: Int,
        l: Long
    ) {
        if (ToolsUtil.isFastDoubleClick) {
            return
        }
        onNoDoubleItemClick(adapterView, view, position, l)
    }

    abstract fun onNoDoubleItemClick(
        adapterView: AdapterView<*>?,
        view: View?,
        position: Int,
        id: Long
    )
}

后面将view的点击事件设置为以上的类或者其子类,就可以防止连续点击了。

github地址:https://gitee.com/stonezry/AndroidDemo

你可能感兴趣的:(android防止连续点击的简单实现(kotlin))