View 事件分发机制

看完《Android开发艺术探索》的 View的事件分发章节后,今天决定实践了一下,尝试制作 QQ Android 版中的简易右划返回,以此深入了解事件分发机制。

View 的事件分发主要涉及三个方法:

  1. public boolean dispatchTouchEvent(MotionEvent ev)
  2. public boolean onInterceptTouchEvent(MotionEvent ev)
  3. public boolean onTouchEvent(MotionEvent ev)

其中第一个方法是 View 在传递事件时使用的,一般不需要我们重写。想要响应滑动事件,主要是要onInterceptTouchEventonTouchEvent 这两个方法上下文章。

首先我们点入 onInterceptTouchEvent 方法查看源码,可以看到一长串的注释。

    /**
     * Implement this method to intercept all touch screen motion events.  This
     * allows you to watch events as they are dispatched to your children, and
     * take ownership of the current gesture at any point.
     *
     * 

Using this function takes some care, as it has a fairly complicated * interaction with {@link View#onTouchEvent(MotionEvent) * View.onTouchEvent(MotionEvent)}, and using it requires implementing * that method as well as this one in the correct way. Events will be * received in the following order: * *

    *
  1. You will receive the down event here. *
  2. The down event will be handled either by a child of this view * group, or given to your own onTouchEvent() method to handle; this means * you should implement onTouchEvent() to return true, so you will * continue to see the rest of the gesture (instead of looking for * a parent view to handle it). Also, by returning true from * onTouchEvent(), you will not receive any following * events in onInterceptTouchEvent() and all touch processing must * happen in onTouchEvent() like normal. *
  3. For as long as you return false from this function, each following * event (up to and including the final up) will be delivered first here * and then to the target's onTouchEvent(). *
  4. If you return true from here, you will not receive any * following events: the target view will receive the same event but * with the action {@link MotionEvent#ACTION_CANCEL}, and all further * events will be delivered to your onTouchEvent() method and no longer * appear here. *
* * @param ev The motion event being dispatched down the hierarchy. * @return Return true to steal motion events from the children and have * them dispatched to this ViewGroup through onTouchEvent(). * The current target will receive an ACTION_CANCEL event, and no further * messages will be delivered here. */

根据注释我们就可以得知完整的事件传递的逻辑:

事件流从 ACTION_DOWN 开始到 ACTION_UP 结束。

首先,进入 onInterceptTouchEvent 方法,返回 true 的话子 View 将不能收到事件,并且 onInterceptTouchEvent 也将不再收到事件流,事件处理全部交由 onTouchEvent 处理。返回 false 的话,事件会继续传递给子 View,并且onInterceptTouchEvent 将持续收到事件流,如果在事件流中途拦截事件,那么 onInterceptTouchEvent 及子 View (会收到 ACTION_CANCEL)之后也将不在得到事件流,事件流交由同样交由 onTouchEvent 处理。

上面说的是有子 View 的情况,如果没有子 View (或者说子 View 没有处理) 的话,事件会回到 onTouchEvent 方法,返回 true 的话,之后的事件就交由它处理,否则就继续传递给父 View 处理。

假若事件传递到了 onTouchEvent 方法, 并且该方法第一次返回了 true,那么之后的事件将一直交由它处理,除非事件被父 View 拦截,将收到 ACTION_CANCEL ,返回 false 将永远收不到事件流。

根据以上描述,我们很容易就可以得出要实现滑动返回需要做的事。首先,在 onInterceptTouchEvent 方法中拦截右滑事件,之后在 onTouchEvent中处理滑动事件就可以了。

于是一个简易的右滑返回控件就写好了,代码如下:

public class SwipeBackLayout extends FrameLayout {
    public static final String TAG = SwipeBackLayout.class.getSimpleName();
    private int lastX = 0;
    private int lastY = 0;
    private boolean isRight = true;

    public SwipeBackLayout(Context context) {
        super(context);
    }

    public SwipeBackLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SwipeBackLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (MotionEvent.ACTION_DOWN == ev.getAction()) {
            // 每次事件流重置
            lastX = (int) ev.getX();
            lastY = (int) ev.getY();
            isRight = true;
        }

        if (MotionEvent.ACTION_MOVE == ev.getAction()) {
            // 拦截右滑
            int deltaX = (int) (ev.getX() - lastX);
            int deltaY = Math.abs((int) (ev.getY() - lastY));
            if (deltaX > 0 && deltaX - deltaY > 0) {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (MotionEvent.ACTION_MOVE == event.getAction()) {
            // 判断右滑
            int deltaX = (int) (event.getX() - lastX);
            int deltaY = Math.abs((int) (event.getY() - lastY));
            if (deltaX < 0 || deltaX - deltaY < 0) {
                isRight = false;
            }
        }

        if (MotionEvent.ACTION_UP == event.getAction()) {
            // 触发动作,用 Toast 代替
            if (isRight) {
                Toast.makeText(getContext(), "触发右滑事件", Toast.LENGTH_SHORT).show();
            }
        }

        return true;
    }
}

你可能感兴趣的:(View 事件分发机制)