android快速点击打开两个相同界面的解决办法

2019-01-08  本文已影响0人  张磊_9c5e

一.第一种解决方法

在父类activity中重写事件分发的方法dispatchTouchEvent()
原理:
当在activity中快速点击某个控件,时间间隔不超过300ms,此时activity拦截click事件,这是点击的view将得不到响应,代码如下:

public  static final long DEFAULT_TIME = 300;
@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isFastDoubleClick()) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }


    public boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        lastClickTime = time;
        return timeD <= DEFAULT_TIME;
    }

二.第二种解决方法

1.写一个工具类:

public class Utils {
/**
     * @param target      防止多次点击的View
     * @param defaultTime 超时时间
     * @return
     */
    public static boolean isInvalidClick(@NonNull View target, @IntRange(from = 0) long defaultTime) {
        long curTimeStamp = System.currentTimeMillis();
        long lastClickTimeStamp = 0;
        Object o = target.getTag(R.id.invalid_click);
        if (o == null) {
            target.setTag(R.id.invalid_click, curTimeStamp);
            return false;
        }
        lastClickTimeStamp = (Long) o;
        boolean isInvalid = curTimeStamp - lastClickTimeStamp < defaultTime;
        if (!isInvalid) {
            target.setTag(R.id.invalid_click, curTimeStamp);
        }
        return isInvalid;
    }
}

2.在values下,新建一个ids.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="invalid_click" type="id" />
</resources>

3.在点击事件中调用:

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isInvalidClick(v, 300))
                    return;

                Toast.makeText(MainActivity.this, "hello world!", Toast.LENGTH_SHORT).show();
            }
        });
上一篇下一篇

猜你喜欢

热点阅读