Android 一个好用的防止重复点击的工具类

先说明,我不是原创,我都不记得从哪抄的了很久了,用了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属性缺失?来,给你补上


放到ids.xml下就可以啦

你可能感兴趣的:(Android 一个好用的防止重复点击的工具类)