?外部拦截法
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean intercepted =false;
int x = (int) ev.getX();
int y = (int) ev.getY();
switch (ev.getAction()){
case MotionEvent.ACTION_DOWN:
intercepted = false;
break;
case MotionEvent.ACTION_MOVE:
if(父容器需要当前点击事件) {
intercepted = true;
}else {
intercepted = false;
}
break;
case MotionEvent.ACTION_UP:
intercepted = false;
break;
default:
break;
}
mLastXintercept = x;
mLastYintercept = y;
return intercepted;
}
其中ACTION_DOWN事件必须返回false,因为父容器一旦拦截就无法传递到子元素了,最后是ACTION_UP事件返回false,父容器拦截move,up事件也会拦截
内部拦截法
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int x = (int) ev.getX();
int y = (int) ev.getY();
switch (ev.getAction()){
case MotionEvent.ACTION_DOWN:
parent.requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
int delatX = x - mLastX;
int delatY = y - mLastY;
if(父容器需要) {
parent.requestDisallowInterceptTouchEvent(false);
}
break;
case MotionEvent.ACTION_UP:
break;
default:
break;
}
mLastX = x;
mLastY = y;
return intercepted;
}
父容器也要拦截除了ACTION_DOWN以外的事件,这样子元素调用
parent.requestDisallowInterceptTouchEvent(false);时,父元素才能继续拦截所需事件
而ACTION_DOWN事件不受这个标记位影响,所以父容器一旦拦截ACTION_DOWN,事件就无法传递到子元素中了
|