先说明,我不是原创,我都不记得从哪抄的了很久了,用了4年感觉不错,今天看有人还对防止重复点击没有好的解决方案,所以发到网上记录一下,大牛们请绕道。
/**
* 防抖动点击
*
* @author yanjin
*/
public class AntiShakeUtils {
private final static long INTERNAL_TIME = 1000;
/**
* Whether this click event is invalid.
*
* @param target target view
* @return true, invalid click event.
* @see #isInvalidClick(View, long)
*/
public static boolean isInvalidClick(@NonNull View target) {
return isInvalidClick(target, INTERNAL_TIME);
}
/**
* Whether this click event is invalid.
*
* @param target target view
* @param internalTime the internal time. The unit is millisecond.
* @return true, invalid click event.
*/
public static boolean isInvalidClick(@NonNull View target, @IntRange(from = 0) long internalTime) {
long curTimeStamp = System.currentTimeMillis();
long lastClickTimeStamp = 0;
Object o = target.getTag(R.id.last_click_time);
if (o == null){
target.setTag(R.id.last_click_time, curTimeStamp);
return false;
}
lastClickTimeStamp = (Long) o;
boolean isInvalid = curTimeStamp - lastClickTimeStamp < internalTime;
if (!isInvalid)
target.setTag(R.id.last_click_time, curTimeStamp);
return isInvalid;
}
}
调用也很简单,比如我们在点击事件中
@Override
public void onClick(View v) {
super.onClick(v);
try {
if (v == location_address) {
if(AntiShakeUtils.isInvalidClick(v)){
return;//防止重复点击
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
直接返回
对了,考代码的时候是不是有个id属性缺失?来,给你补上
<item name="last_click_time" type="id" />
放到ids.xml下就可以啦
网友评论