美文网首页
滑动冲突的解决

滑动冲突的解决

作者: jacky123 | 来源:发表于2016-07-12 19:32 被阅读39次

外部拦截法

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;
    }
}

相关文章

网友评论

      本文标题:滑动冲突的解决

      本文链接:https://www.haomeiwen.com/subject/gulsjttx.html