开发当中经常需要对按钮控制防止重复点击,写了一个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();
}
});
网友评论