public class ButtonUtils {
private static long lastClickTime = 0;
private static long DIFF = 1000;
private static int lastButtonId = -1;
/**
* 判断两次点击的间隔,如果小于1000,则认为是多次无效点击
*
* @return
*/
public static boolean isFastDoubleClick() {
return isFastDoubleClick(-1, DIFF);
}
/**
* 判断两次点击的间隔,如果小于1000,则认为是多次无效点击
*
* @return
*/
public static boolean isFastDoubleClick(int buttonId) {
return isFastDoubleClick(buttonId, DIFF);
}
/**
* 判断两次点击的间隔,如果小于diff,则认为是多次无效点击
*
* @param diff
* @return
*/
public static boolean isFastDoubleClick(int buttonId, long diff) {
long time = System.currentTimeMillis();
long timeD = time - lastClickTime;
if (lastButtonId == buttonId && lastClickTime > 0 && timeD < diff) {
return true;
}
lastClickTime = time;
lastButtonId = buttonId;
return false;
}
}
- 在BaseActivity里重写dispatchTouchEvent方法
/**
* 防止view重复点击
*/
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
if (ev?.action == MotionEvent.ACTION_DOWN) {
// 判断连续点击事件时间差
if (ButtonUtils.isFastDoubleClick()) {
return true
}
}
return super.dispatchTouchEvent(ev)
}
思路:通过事件分发机制来拦截点击事件
注:dispatchTouchEvent()返回true,后续事件(ACTION_MOVE、ACTION_UP)会再传递,如果返回false,dispatchTouchEvent()就接收不到ACTION_UP、ACTION_MOVE。
网友评论