美文网首页
全局设置 防止view重复点击

全局设置 防止view重复点击

作者: 执念蓝枫 | 来源:发表于2019-07-22 17:01 被阅读0次
  • 根据点击时间判断是否是初次点击的工具类
public class ButtonUtils {
    private static long lastClickTime = 0;
    private static long DIFF = 1000;
    private static int lastButtonId = -1;

    /**
     * 判断两次点击的间隔,如果小于1000,则认为是多次无效点击
     *
     * @return
     */
    public static boolean isFastDoubleClick() {
        return isFastDoubleClick(-1, DIFF);
    }

    /**
     * 判断两次点击的间隔,如果小于1000,则认为是多次无效点击
     *
     * @return
     */
    public static boolean isFastDoubleClick(int buttonId) {
        return isFastDoubleClick(buttonId, DIFF);
    }

    /**
     * 判断两次点击的间隔,如果小于diff,则认为是多次无效点击
     *
     * @param diff
     * @return
     */
    public static boolean isFastDoubleClick(int buttonId, long diff) {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (lastButtonId == buttonId && lastClickTime > 0 && timeD < diff) {
            return true;
        }
        lastClickTime = time;
        lastButtonId = buttonId;
        return false;
    }

}
  • 在BaseActivity里重写dispatchTouchEvent方法
/**
     * 防止view重复点击
     */
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {

        if (ev?.action == MotionEvent.ACTION_DOWN) {
            // 判断连续点击事件时间差
            if (ButtonUtils.isFastDoubleClick()) {
                return true
            }
        }
        return super.dispatchTouchEvent(ev)
    }
思路:通过事件分发机制来拦截点击事件
注:dispatchTouchEvent()返回true,后续事件(ACTION_MOVE、ACTION_UP)会再传递,如果返回false,dispatchTouchEvent()就接收不到ACTION_UP、ACTION_MOVE。

相关文章

网友评论

      本文标题:全局设置 防止view重复点击

      本文链接:https://www.haomeiwen.com/subject/czqxcctx.html