美文网首页
Android 防止控件重复点击

Android 防止控件重复点击

作者: 越努力越幸运阳 | 来源:发表于2018-01-11 18:15 被阅读0次

开发当中经常需要对按钮控制防止重复点击,写了一个util类,简单方便实用。

public class ClickUtil {
    private final View view;
    private long time = 0;

    public ClickUtil(View view) {
        this.view = view;
    }

    public static ClickUtil clicks(@NonNull View view) {
        checkNotNull(view, "view == null");
        return new ClickUtil(view);
    }

    public ClickUtil throttleFirst(long time) {
        this.time = time;
        return this;
    }

    private long endTime = 0;

    private synchronized boolean isThrottle() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - endTime >= time) {
            endTime = System.currentTimeMillis();
            return false;
        }
        return true;
    }

    public void setOnClickListener(@NonNull final View.OnClickListener listener) {
        checkNotNull(listener, "listener == null");
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isThrottle()) {
                    listener.onClick(v);
                }
            }
        });
    }

    private static void checkNotNull(Object value, String message) {
        if (value == null) {
            throw new NullPointerException(message);
        }
    }
}

在看下怎么使用,控制2秒内的重复点击都无效

ClickUtil.clicks(bt_login).throttleFirst(2000)
                .setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });

相关文章

网友评论

      本文标题:Android 防止控件重复点击

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