外部拦截法
public boolean onInterceptTouchEvent(MotionEvent e){
boolean intercept = false;
int x = (int) e.getX();
int y = (int) e.getY();
switch(e.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;
}
mLastXIntercept = x;
mLastYIntercept = y;
return intercepted;
}
内部拦截法
1.在子View中
public boolean dispatchTouchEvent(MotionEvent event){
int x = (int) e.getX();
int y = (int) e.getY();
switch(e.getAction){
case MotionEvent.ACTION_DOWN:
getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
int deltaX = x - mLastX;
int deltaY = y - mLastY;
if(父控件需要当前事件){
getParent().requestDisallowInterceptTouchEvent(false);
}
break;
case MotionEvent.ACTION_UP:
break;
}
mLastX = x;
mLastY = y;
return Super.dispatchTouchEvent(event);
}
2.在父View中
一旦父容器拦截了 ACTION_DOWN 事件,事件将无法传递到子View中。
public boolean onInterceptTouchEvent(MotionEvent event){
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN){
return false;
} else{
return true;
}
}
网友评论