android-----事件分发机制

我们首先从一个简单的例子开始分析

                button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View view) {
				System.out.println("执行onClick");
			}
		});
		button.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View view, MotionEvent event) {
				System.out.println("执行onTouch的"+event.getAction());
				return false;
			}
		});

这段代码经常出现在我们绑定按钮监听事件的情况下,但是你能确定当同时为按钮绑定onClick和onTouch事件的情况下会首先执行哪个事件么?我们来看看输出结果:

04-29 22:52:43.411: I/System.out(845): 执行onTouch的0
04-29 22:52:43.481: I/System.out(845): 执行onTouch的1
04-29 22:52:43.572: I/System.out(845): 执行onClick

也许你的手会抖几下,那么你的输出结果将会多几个执行onTouch的2的值;

但是不管怎么说,首先还是会先执行的onTouch方法,随后onTouch执行结束才会执行onClick方法,除此之外,我们还发现onTouch方法是有返回值的,上面实例中,返回值是false,假如我们将该返回值设置为true的话,程序的输出结果是:

04-29 23:25:15.082: I/System.out(966): 执行onTouch的0
04-29 23:25:15.161: I/System.out(966): 执行onTouch的1

不管你怎么点击按钮,都不会执行onClick方法,这更加印证了onTouch优先于onClick方法执行,当onTouch返回值设置为true的时候我们可以理解为onTouch方法将事件消费掉了,不再会传递下去;

平常的应用就是这样啦,接下来从源码的角度分析一下造成这种情况的原因:

首先分析之前应该明白的一点就是触摸屏事件首先传递到的是ViewGroup的,他是我们平常的各种布局的父类或者间接父类,这点可以从android官方文档中看到:

android-----事件分发机制_第1张图片

可以看出,LinearLayout以及各种布局文件都是他的子类,ViewGroup是一组View的集合,他包含很多子View和子ViewGroup,因此在探讨ViewGroup的事件分发机制之前我们首先应该看看View的事件分发机制;

首先应该明白的是每当触摸一个控件的时候都会调用该控件的dispatchTouchEvent方法,以上面的Button类为例,发现Button类中不存在dispatchTouchEvent方法,那么就到他的父类TextView中寻找,发现TextView中也不存在这个方法,随后到TextView的父类View中去寻找,终于找到啦!

public boolean dispatchTouchEvent(MotionEvent event) {
        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }

        if (onFilterTouchEventForSecurity(event)) {
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                return true;
            }

            if (onTouchEvent(event)) {
                return true;
            }
        }

        if (mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }
        return false;
    }

这段源码的核心代码在第9行,他会首先查看下li是否为null以及li中的mOnTouchListener是否为null,(mViewFlags & ENABLED_MASK)==ENABLE判断当前控件是否是ENABLE的,那么这里的li到底是什么呢?第8行看到,li是等于 mListenerInfo的ListenerInfo对象,那么mListenerInfo是在哪里赋值的呢?

ListenerInfo getListenerInfo() {
        if (mListenerInfo != null) {
            return mListenerInfo;
        }
        mListenerInfo = new ListenerInfo();
        return mListenerInfo;
    }
可以看到是调用getListenerInfo方法来生成的,那么li中的属性mOnTouchListener是在哪里赋值的呢?

 public void setOnTouchListener(OnTouchListener l) {
        getListenerInfo().mOnTouchListener = l;
    }
发现就是将我们平常使用setOnTouchListener的参数设置为了li的mOnTouchListener属性,那么当li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED为true的时候会执行最后一个条件判断语句,也就是我们在setOnTouchListener里面经常重写的那个方法onTouch啦,这个方法会有一个返回值,当返回值为true的时候执行if语句块中的内容,直接返回true,那么dispatchTouchEvent方法执行结束,也就是整个事件分发已经结束了,所以上面例子中当我们将onTouch方法的返回值设置为true的时候,并不会执行onClick方法,因为程序在这个if语句块中已经返回了;

那么我们有理由相信第14行的if语句块中的onTouchEvent方法肯定与onClick方法有关系,来看看源码:

    public boolean onTouchEvent(MotionEvent event) {
        final int viewFlags = mViewFlags;

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
                setPressed(false);
            }
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return (((viewFlags & CLICKABLE) == CLICKABLE ||
                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
        }

        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        if (((viewFlags & CLICKABLE) == CLICKABLE ||
                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
                        // take focus if we don't have it already and we should in
                        // touch mode.
                        boolean focusTaken = false;
                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            focusTaken = requestFocus();
                        }

                        if (prepressed) {
                            // The button is being released before we actually
                            // showed it as pressed.  Make it show the pressed
                            // state now (before scheduling the click) to ensure
                            // the user sees it.
                            setPressed(true);
                       }

                        if (!mHasPerformedLongPress) {
                            // This is a tap, so remove the longpress check
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                // Use a Runnable and post this rather than calling
                                // performClick directly. This lets other visual state
                                // of the view update before click actions start.
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    performClick();
                                }
                            }
                        }

                        if (mUnsetPressedState == null) {
                            mUnsetPressedState = new UnsetPressedState();
                        }

                        if (prepressed) {
                            postDelayed(mUnsetPressedState,
                                    ViewConfiguration.getPressedStateDuration());
                        } else if (!post(mUnsetPressedState)) {
                            // If the post failed, unpress right now
                            mUnsetPressedState.run();
                        }
                        removeTapCallback();
                    }
                    break;

                case MotionEvent.ACTION_DOWN:
                    mHasPerformedLongPress = false;

                    if (performButtonActionOnTouchDown(event)) {
                        break;
                    }

                    // Walk up the hierarchy to determine if we're inside a scrolling container.
                    boolean isInScrollingContainer = isInScrollingContainer();

                    // For views inside a scrolling container, delay the pressed feedback for
                    // a short period in case this is a scroll.
                    if (isInScrollingContainer) {
                        mPrivateFlags |= PFLAG_PREPRESSED;
                        if (mPendingCheckForTap == null) {
                            mPendingCheckForTap = new CheckForTap();
                        }
                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    } else {
                        // Not inside a scrolling container, so show the feedback right away
                        setPressed(true);
                        checkForLongClick(0);
                    }
                    break;

                case MotionEvent.ACTION_CANCEL:
                    setPressed(false);
                    removeTapCallback();
                    removeLongPressCallback();
                    break;

                case MotionEvent.ACTION_MOVE:
                    final int x = (int) event.getX();
                    final int y = (int) event.getY();

                    // Be lenient about moving outside of buttons
                    if (!pointInView(x, y, mTouchSlop)) {
                        // Outside button
                        removeTapCallback();
                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
                            // Remove any future long press/tap checks
                            removeLongPressCallback();

                            setPressed(false);
                        }
                    }
                    break;
            }
            return true;
        }

        return false;
    }

这个方法有点长,我们仅看核心部分,首先第4行的if语句的作用在于可能当前View是disabled的,但是仍然是可点击的,这种情况下我们同样需要消费掉这个Touch事件,只不过不对这个Touch事件做任何事情而已,只是返回true而已;第20行,如果当前控件是可点击的话,则进入switch里面判断当前事件的类型,我们进入MotionEvent.ACTION_UP里面查看将会发现经过层层if判断,最终将会执行第54行的performClick方法,进入这个方法里面看看执行了些什么操作:

public boolean performClick() {
        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);

        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            return true;
        }

        return false;
    }
第5行判断li以及他的属性mOnClickListener是否为null,聪明的你一定会猜到mOnClickListener的赋值操作和前面的mOnTouchListener将是一样的

public void setOnClickListener(OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }
没错吧,最后执行他的onClick方法就行啦,当然平时我们是重写这个方法的;

一切都变的那么明了了,其实如果说onClick方法执行在onTouch方法之后具体有多后呢?刚刚就已经看出来了,在我们的手指即将离开控件的时候,即MotionEvent.ACTION_UP情况下才会执行onClick方法;

好啦,View的事件分发过程就已经介绍结束啦,我们做个总结一下马上看看事件是怎么从ViewGroup传递到View的:

首先在每个控件View上面触发事件的时候都会首先执行dispatchTouchEvent方法,接着在这个方法里面首先会查看是否有touch事件绑定,有的话直接执行该touch事件的onTouch方法,并且如果onTouch方法返回的是true的话,则dispatchTouchEvent方法直接返回true,执行结束;如果没有绑定touch事件或者onTouch方法返回false的话,则执行onTouchEvent方法,在这个方法switch的MotionEvent.ACTION_UP这个case情况下调用performClick,进而调用onClick方法执行点击事件,执行结束之后返回true,最后dispatchTouchEvent方法返回,事件分发结束;
前面已经提到过事件是从ViewGroup传递到View的,那么这个过程又是怎么的呢?

来,我们看个例子:

                button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View view) {
				System.out.println("执行了Button的onClick方法");
			}
		});
		relativeLayout.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				System.out.println("执行了RelativeLayout的onTouch方法,action为: "+arg1.getAction());
				return false;
			}
		});

我们分别为Button以及RealtiveLayout设置了Click监听事件

点击button的输出为:

04-30 02:46:45.131: I/System.out(1164): 执行了Button的onClick方法
点击屏幕空白区域的输出为:
04-30 02:52:57.305: I/System.out(1220): 执行了RelativeLayout的onTouch方法,action为: 0
也就是当我们直接点击button按钮的时候是不会执行RelativeLayout的onTouch方法的,在这里Button按钮相当于是View,而RelativeLayout相当于ViewGroup,前面已经提到事件是从ViewGroup传递到View的,事实依据就是:

假如我们认为是从View传递到ViewGroup,那么只要我们找到一种情况就是点击View控件的时候触发的只是ViewGroup绑定的方法而不是View绑定的方法的话,我们就可以认为是ViewGroup消费了事件,因此事件是ViewGroup到View的,接下来举出这样的例子:

我们自己来实现一个RelativeLayout,并且重写onInterceptTouchEvent方法,这个方法的原型是在ViewGroup里面的,原型见下:

  public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }
就是这么简单,只是返回false而已;

我们自定义的RelativeLayout命名为MyRelativeLayout:

public class MyRelativeLayout extends RelativeLayout{

	public MyRelativeLayout(Context context) {
		super(context);
	}
	public MyRelativeLayout(Context context, AttributeSet attrs) {
		super(context,attrs);
	}
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		return true;
	}
}
可见我们把onInterceptTouchEvent的返回值修改成了true,在将自定义布局引入到布局文件之后,重新执行程序会发现不管我们是点击button按钮还是点击空白区域输出的结果都是:

04-30 03:12:36.901: I/System.out(1310): 执行了RelativeLayout的onTouch方法,action为: 0
这也就是说当我们把onInterceptTouchEvent的返回值修改成了true,可以理解为当前布局也就是ViewGroup消费了事件,事件没有再向下传递了,也就说明了事件是从ViewGroup传递到View的啦!

那么上面我们说过触发View控件的事件首先会触发其dispatchTouchEvent事件,那么其实实际上呢,触发这个方法的本质上就已经可以说成是ViewGroup触发的啦,那么我们进入ViewGroup的源码中看看他的dispatchTouchEvent方法是什么样子的呢?

@Override
    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;

            // Handle an initial down.
            if (actionMasked == MotionEvent.ACTION_DOWN) {
                // Throw away all previous state when starting a new touch gesture.
                // The framework may have dropped the up or cancel event for the previous gesture
                // due to an app switch, ANR, or some other state change.
                cancelAndClearTouchTargets(ev);
                resetTouchState();
            }

            // Check for interception.
            final boolean intercepted;
            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {
                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                if (!disallowIntercept) {
                    intercepted = onInterceptTouchEvent(ev);
                    ev.setAction(action); // restore action in case it was changed
                } else {
                    intercepted = false;
                }
            } else {
                // There are no touch targets and this action is not an initial down
                // so this view group continues to intercept touches.
                intercepted = true;
            }

            // Check for cancelation.
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;

            // Update list of touch targets for pointer down, if needed.
            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);
                        // Find a child that can receive the event.
                        // Scan children from front to back.
                        final View[] children = mChildren;

                        final boolean customOrder = isChildrenDrawingOrderEnabled();
                        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) {
                                // Child is already receiving touch within its bounds.
                                // Give it the new pointer in addition to the ones it is handling.
                                newTouchTarget.pointerIdBits |= idBitsToAssign;
                                break;
                            }

                            resetCancelNextUpFlag(child);
                            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) {
                        // Did not find a child to receive the event.
                        // Assign the pointer to the least recently added target.
                        newTouchTarget = mFirstTouchTarget;
                        while (newTouchTarget.next != null) {
                            newTouchTarget = newTouchTarget.next;
                        }
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }

            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary 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;
                        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;
                }
            }

            // Update list of touch targets for pointer up or cancel, if needed.
            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;
    }
同样源码好长,我们只看核心:

第46行我们看到if判断的条件是只要canceled和intercepted都为false的话,就会执行if语句块的内容,而intercepted的值正是前面我们通过onInterceptTouchEvent方法返回的值,那么我们有理由相信按钮的点击事件肯定是在这个if语句块中执行的,因为前面我们将onInterceptTouchEvent的返回值改为true之后,if不会执行其语句块,也就意味着直接屏蔽了按钮点击事件了,在if语句块中经过层层计算最后到达第85行执行了dispatchTransformedTouchEvent方法,这个方法也属于ViewGroup,在这个方法里面肯定会出现调用View的dispatchTouchEvent方法,我们可以看看dispatchTransformedTouchEvent的源码:

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

        // Calculate the number of pointers to deliver.
        final int oldPointerIdBits = event.getPointerIdBits();
        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;

        // If for some reason we ended up in an inconsistent state where it looks like we
        // might produce a motion event with no pointers in it, then drop the event.
        if (newPointerIdBits == 0) {
            return false;
        }

        // 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.
        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;
                    event.offsetLocation(offsetX, offsetY);

                    handled = child.dispatchTouchEvent(event);

                    event.offsetLocation(-offsetX, -offsetY);
                }
                return handled;
            }
            transformedEvent = MotionEvent.obtain(event);
        } else {
            transformedEvent = event.split(newPointerIdBits);
        }

        // Perform any necessary transformations and dispatch.
        if (child == null) {
            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());
            }

            handled = child.dispatchTouchEvent(transformedEvent);
        }

        // Done.
        transformedEvent.recycle();
        return handled;
    }
同样挺长的,我们只看重点,在第11行、13行、37行、43行、56行、65行可能会执行不同判断条件下的View的dispatchTouchEvent方法,但是不管怎么说这个方法是从ViewGroup方法里面的 dispatchTouchEvent调用的,接下来的事件分发就是最开始我们介绍的View的事件分发过程啦,至此整个事件分发过程介绍结束!

总结一下整个事件分发流程是这样子的:

ViewGroup(所有布局的父类)通过调用自己的dispatchTouchEvent方法,将事件传递给自己里面的View,View自己调用自己的dispatchTouchEvent方法来进行事件处理,细节方面上面已经总结过啦!




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