美文网首页
android防止2s内重复点击事件

android防止2s内重复点击事件

作者: 心中有梦丶身边有你 | 来源:发表于2019-04-27 20:21 被阅读0次
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);
        }
    }
}

Activity中调用方法


              //2秒内重复点击判断 btnLogin为你的按钮组件
                ClickUtil.clicks(btnLogin).throttleFirst(2000)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                /点击事件
                            }
                        });

相关文章

网友评论

      本文标题:android防止2s内重复点击事件

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