Android的Touch系统简介(一)

原创 2014年05月20日 19:07:30

一、Android touch事件的相关概念

用户的Touch事件被包装成MotionEvent

用户当前的touch事件主要类型有:

ACTION_DOWN: 表示用户开始触摸.

 ACTION_MOVE: 表示用户在移动(手指或者其他)

 ACTION_UP:表示用户抬起了手指 

ACTION_CANCEL:表示手势被取消了,一些关于这个事件类型的讨论见:http://stackoverflow.com/questions/11960861/what-causes-a-motionevent-action-cancel-in-android 

ACTION_OUTSIDE: 表示用户触碰超出了正常的UI边界.

ACTION_POINTER_DOWN:有一个非主要的手指按下了.

ACTION_POINTER_UP:一个非主要的手指抬起来了

touch事件的元数据包括:

touch的位置

手指的个数

touch事件的时间

一个touch手势被定义为以ACTION_DOWN开始和以 ACTION_UP结束。


二、Touch事件的处理流程

当用户触摸屏幕时,触发Activity调用dispatchTouchEvent

事件对象会按自顶向下的顺序在View Tree中传递

     父View(ViewGroups)会调用dispatchTouchEvent将Event传递给子View    

    Event在任何时候都可能被拦截

事件流会顺着View链递归向下传递直到被消耗

若某个View想处理touch事件,必须先消耗ACTION_DOWN。考虑到效率,后续的事件将不会向下传递。

若某个事件未被消耗,最后会被Activity的onTouchEvent()消耗

若任何View或ViewGroup设置了OnTouchListener,touch事件将被拦截。


Activity.dispathcTouchEvent()的源码分析:

 /**
     * Called to process touch screen events. You can override this to
     * intercept all touch screen events before they are dispatched to the
     * window. Be sure to call this implementation for touch screen events
     * that should be handled normally.
     *
     * @param ev The touch screen event.
     *
     * @return boolean Return true if this event was consumed.
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

由代码可以看出,对于应用层,该函数在touch事件发生后首先被调用。onUserInteraction()是一个空函数,可被用户重载以进行相关处理。Event随后将被传递到关联到root view的window。若子view消耗了该Event,则返回true,否则Event最后被Activity的onTouchEvent()消耗。

ViewGroup.dispatchTouchEvent()的源码分析如下:

public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
        }
        boolean handled = false;
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;
            // 处理初始的down事件
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                //当新开始一个touch事件时,抛弃先前的touch状态
                //当app切换,发生ANR或一些其他的touch状态发生时,framework会丢弃或取消先前的touch状态
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }
            // 检查是否进行事件拦截
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    //回调onInterceptTouchEvent(),返回false表示不拦截touch,否则拦截touch事件。
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            } else {
                //没有touch事件的传递对象,同时touch动作不是初始动作down,所以ViewGroup继续拦截事件
                intercepted = true;
            }
            // 检查cancel事件
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;
            // 如果有第二个手指touch,更新touch目标列表。touch目标列表是一个View数组
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            TouchTarget newTouchTarget = null;
            boolean alreadyDispatchedToNewTouchTarget = false;
            if (!canceled && !intercepted) {
                if (actionMasked == MotionEvent.ACTION_DOWN
                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                    final int actionIndex = ev.getActionIndex(); // always 0 for down
                    final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
                            : TouchTarget.ALL_POINTER_IDS;
                    // Clean up earlier touch targets for this pointer id in case they
                    // have become out of sync.
                    removePointersFromTouchTargets(idBitsToAssign);
                    final int childrenCount = mChildrenCount;
                    if (newTouchTarget == null && childrenCount != 0) {
                        final float x = ev.getX(actionIndex);
                        final float y = ev.getY(actionIndex);
                        // 找到一个能接受Event的子View,再对子View的View树进行遍历
                        final View[] children = mChildren;
                        final boolean customOrder = isChildrenDrawingOrderEnabled();
                        //判断每个子View是否是TouchTarget,若是则添加到TouchTarget链表中
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = customOrder ?
                                    getChildDrawingOrder(childrenCount, i) : i;
                            final View child = children[childIndex];
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                continue;
                            }
                            newTouchTarget = getTouchTarget(child);
                            if (newTouchTarget != null) {
                                // 若子View处于touch目标中,同时已经接收了touch事件,则为器增加新的touch点
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }
                            resetCancelNextUpFlag(child);
                            //把MotionEvent的点坐标转换到子View的坐标系中,为ViewGroup创建一个新TouchTarget,TouchTarget包含了子View
                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                                // Child wants to receive touch within its bounds.
                                mLastTouchDownTime = ev.getDownTime();
                                mLastTouchDownIndex = childIndex;
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }
                        }
                    }
                    if (newTouchTarget == null && mFirstTouchTarget != null) {
                        // 没有发现接收event的子View,把Touch点赋给最早添加到TouchTarget链中的对象
                        newTouchTarget = mFirstTouchTarget;
                        while (newTouchTarget.next != null) {
                            newTouchTarget = newTouchTarget.next;
                        }
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }
            // 传递给touch目标
            if (mFirstTouchTarget == null) {
                // 若没有Touch目标,则把自己当成一个View,调用
                handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
            } else {
                // Dispatch to touch targets, excluding the new touch target if we already
                // dispatched to it. Cancel touch targets if necessary.
                TouchTarget predecessor = null;
                TouchTarget target = mFirstTouchTarget;
                while (target != null) {
                    final TouchTarget next = target.next;
                    //若已被处理,则忽略。
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                        handled = true;
                    } else {
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                        //传递给子View处理
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                            handled = true;
                        }
                        if (cancelChild) {
                            if (predecessor == null) {
                                mFirstTouchTarget = next;
                            } else {
                                predecessor.next = next;
                            }
                            target.recycle();
                            target = next;
                            continue;
                        }
                    }
                    predecessor = target;
                    target = next;
                }
            }
            // 若在触摸点发生了up或cancel,则更新TouchTarget链表
            if (canceled
                    || actionMasked == MotionEvent.ACTION_UP
                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
                resetTouchState();
            } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
                final int actionIndex = ev.getActionIndex();
                final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
                removePointersFromTouchTargets(idBitsToRemove);
            }
        }
        if (!handled && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
        }
        return handled;
    }

ViewGroup中将TouchEvent传递给子View的函数为dispatchTransformedTouchEvent(),源代码如下:

 /**
     * Transforms a motion event into the coordinate space of a particular child view,
     * filters out irrelevant pointer ids, and overrides its action if necessary.
     * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
     */
    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;
        // Canceling motions is a special case. We don't need to perform any transformations
        // or filtering. The important part is the action, not the contents.
        // cancel动作是个特列,无需坐标转换或过滤。
        final int oldAction = event.getAction();
        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            if (child == null) {
                handled = super.dispatchTouchEvent(event);
            } else {
                handled = child.dispatchTouchEvent(event);
            }
            event.setAction(oldAction);
            return handled;
        }
        // 计算将被传递的点的数量。
        final int oldPointerIdBits = event.getPointerIdBits();
        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

        // Motion事件没有对应点,则丢弃这个Motion
        if (newPointerIdBits == 0) {
            return false;
        }

        /*若点的数量一致则无需进行不相关的点坐标转换,调用子View的dispatchTouchEvent*/
        // If the number of pointers is the same and we don't need to perform any fancy
        // irreversible transformations, then we can reuse the motion event for this
        // dispatch as long as we are careful to revert any changes we make.
        // Otherwise we need to make a copy.
        /*该变量用于保存坐标转换后的MoetionEvent*/
        final MotionEvent transformedEvent;
        if (newPointerIdBits == oldPointerIdBits) {
            if (child == null || child.hasIdentityMatrix()) {
                if (child == null) {
                    handled = super.dispatchTouchEvent(event);
                } else {
                    final float offsetX = mScrollX - child.mLeft;
                    final float offsetY = mScrollY - child.mTop;    
                    /*直接对MotionEvent进行坐标变换,将MotionEvent传递下去*/
                    event.offsetLocation(offsetX, offsetY);
                    handled = child.dispatchTouchEvent(event);
                    /*回复MotionEvent*/
                    event.offsetLocation(-offsetX, -offsetY);
                }
                return handled;
            }
            transformedEvent = MotionEvent.obtain(event);
        } else {
            transformedEvent = event.split(newPointerIdBits);
        }
        // Perform any necessary transformations and dispatch.
        if (child == null) {    
            /*调用父类即View的dispatchTouchEvent方法,该方法会调用onTouchEvent*/
            handled = super.dispatchTouchEvent(transformedEvent);
        } else {
            final float offsetX = mScrollX - child.mLeft;
            final float offsetY = mScrollY - child.mTop;
            transformedEvent.offsetLocation(offsetX, offsetY);
            if (! child.hasIdentityMatrix()) {
                transformedEvent.transform(child.getInverseMatrix());
            }
            /*传递给子View处理*/
            handled = child.dispatchTouchEvent(transformedEvent);
        }
        // Done.
        transformedEvent.recycle();
        return handled;
    }
View对象的dispatchTouchEvent代码如下:

  /**
     * Pass the touch screen motion event down to the target view, or this
     * view if it is the target.
     *
     * @param event The motion event to be dispatched.
     * @return True if the event was handled by the view, false otherwise.
     */
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }
        if (onFilterTouchEventForSecurity(event)) {
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            /*先调用listener接口*/
            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                return true;
            }
           /*若MotionEvent未被消耗,则调用View的onTouchEvent *
            * ViewGroup中没有定义onTouchEvent,故做后调用View中的onTouchEvent*/
            if (onTouchEvent(event)) {
                return true;
            }
        }
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }
        return false;
    }

小结:

onInterceptTouchEvent:

onInterceptTouchEvent是在ViewGroup里面定义的,被ViewGroup.dispatchTouchEvent()调用,用于拦截所有的touch事件。默认返回false,表示不拦截touch事件,ViewGroup.dispatchTouchEvent()会调用子View的dispatchTouchEvent,将touch事件传递到子View中。若子View的dispatchTouchEvent 返回false,则ViewGroup的onTouchEvent会被调用;若子View的dispatchTouchEvent 返回true,表示消耗了手势事件,ViewGroup的onTouchEvent则不会被调用。若ViewGroup.onInterceptTouchEvent()返回true,表示Touch事件被拦截,ViewGroup. dispatchTransformedTouchEvent()函数将被调用,该函数会调用super.dispatchTouchEvent(event),即View的dispatchEvent(),该函数首先会调用View.OnTouchListener.onTouch().若listener未消耗Touch事件,则会调用View.onTouchEvent().  


onTouchEvent:

view中定义的方法onTouchEvent默认返回true,表示消耗了一个touch事件,ViewGroup中定义的onTouchEvent默认返回false,表示不处理Touch手势事件。手势事件类型包括ACTION_DOWN,ACTION_MOVE,ACTION_UP,ACTION_CANCEL等事件。


本节及后续都是参考了一篇国外讲义,下载地址:http://download.csdn.net/detail/bigconvience/7376431


Andriod 从源码的角度详解View,ViewGroup的Touch事件的分发机制

今天这篇文章主要分析的是Android的事件分发机制,采用例子加源码的方式让大家深刻的理解Android事件分发的具体情况,虽然网上很多Android的事件分发的文章,有些还写的不错,但是我还是决定写...
  • xiaanming
  • xiaanming
  • 2014年03月24日 09:20
  • 53445

android hover监控鼠标移动事件

android之前对于鼠标光标事件的监控非常少,4.0之后多了一个hover的组件,此组件可以监控鼠标光标在view上的变化。      代码如下: public class HoverDemoA...
  • zhudaozhuan
  • zhudaozhuan
  • 2012年02月10日 18:29
  • 20179

android touch demo

  • 2013年01月30日 09:56
  • 88KB
  • 下载

android Touch

2 3 4 5 6 7 8 9 10 11 version="1.0" encoding="utf-8"?> xmlns:android="http://schemas.andro...
  • freemindhack
  • freemindhack
  • 2014年07月07日 11:44
  • 244

Android触控基础:MotionEvent

之前的文章层从Framework层介绍了Android Touch事件即(MotionEvent)的传递机制。本文将详细介绍MotionEvent的一些成员和方法。了解了MotionEvent对开发一...
  • bigconvience
  • bigconvience
  • 2014年05月22日 19:29
  • 56273

android hover监控鼠标移动事件

原文地址: http://blog.csdn.net/zhudaozhuan/article/details/7249538  android之前对于鼠标光标事件的监控非常少,4....
  • u012587637
  • u012587637
  • 2016年02月18日 17:55
  • 1040

Activity中重载的dispatchTouchEvent 和 onTouchEvent不被调用

0x01. dispatchTouchEvent 和 onTouchEvent不响应dispatchTouchEvent做为Activity的顶层事件分发接口怎么会不响应?肯定是被拦截了!0x02. ...
  • iamcxl369
  • iamcxl369
  • 2017年07月11日 17:57
  • 141

android屏幕touch只响应DOWN事件

public boolean onTouch(View arg0, MotionEvent arg1) { // TODO Auto-generated method stub switch(...
  • sq1018
  • sq1018
  • 2015年03月17日 11:17
  • 994

offsetLocation

/**      * Adjust this event's location.      * @param deltaX Amount to add to the current X coord...
  • fyfcauc
  • fyfcauc
  • 2014年12月05日 18:41
  • 884

Android触摸屏事件派发机制详解与源码分析三(Activity篇)

PS一句:最终还是选择CSDN来整理发表这几年的知识点,该文章平行迁移到CSDN。因为CSDN也支持MarkDown语法了,牛逼啊!【工匠若水 http://blog.csdn.net/yanbobe...
  • yanbober
  • yanbober
  • 2015年05月23日 12:56
  • 17095
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Android的Touch系统简介(一)
举报原因:
原因补充:

(最多只允许输入30个字)