可滚动控件嵌套,有可能导致滑动冲突。
项目中RecyclerView嵌套CoordinatorLayout,导致触摸事件被RecyclerView拦截。
下方代码仅在水平与垂直方向上判断手势方向,后续触摸动作依据第一次判断结果进行处理,继承CoordinatorLayout类,重写dispatchTouchEvent方法
private float downX;
private float downY;
private boolean isDispatch;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
float removingX;//垂直方向移动距离
float removingY;//水平方向移动距离
switch (ev.getAction()){
case MotionEvent.ACTION_DOWN:
downX=ev.getX();
downY=ev.getY();
break;
case MotionEvent.ACTION_MOVE:
removingX = downX - ev.getX();
removingY = downY - ev.getY();
//第一次移动触点,且移动的距离大于10像素
if(!isDispatch && Math.sqrt(removingX*removingX + removingY*removingY) > 10){
/*根据子控件是否拦截,以及移动方向(触点移动,X坐标可能变化,根据垂直方向距离与水平方向距离判断)判断是否拦截事件,
之后所有事件都按照本次判断结果处理*/
isDispatch = super.dispatchTouchEvent(ev) && Math.abs(removingY) > Math.abs(removingX);
//请求父控件不要拦截事件
getParent().requestDisallowInterceptTouchEvent(isDispatch);
return isDispatch;
}
break;
case MotionEvent.ACTION_UP:
//手指抬起后,清除本次触摸时间的拦截结果
isDispatch=false;
break;
}
return super.dispatchTouchEvent(ev);
}