首先 方法类:

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

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐