View的事件分发机制源码解析
来源:互联网 发布:淘宝卖家给买家发短信 编辑:程序博客网 时间:2024/06/05 13:53
上一篇博文,详细讲述了View的事件分发机制,地址为:View的事件分发机制,这篇博客将从源码的角度进一步分析,并正式上一篇博文的结论。
我们知道当一个点击事件产生后,它的传递过程遵循如下顺序:
Activity——>Window——>View
即事件总是先传递给Activity,Activity再传递给Window,最后Window再传递给顶级View。顶级View接受事件后,就会按照事件分发机制去分发事件。
1、Activity对点击事件的分发过程
点击事件用MotionEvent来表示,当一个点击操作发生时,事件最先传递给当前的Activity,由Activity的dispatchTouchEvent方法来进行事件派发,具体的工作是由Activity内部的Window来完成的。window会将事件传递给decor view,decor view一般就是当前界面的底层容器(即setContentView所设置的View的父容器)通过Activity.getWindow.getDecorView()可以获得。先从Activity的dispatchTouchEvent开始分析。
Activity#dispatchTouchEvent
public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }
从上面的源码可以看出,事件开始交给Activity所附属的Window进行分发,如果返回true,整个事件循环就结束了,返回false意味着事件没人处理。也就是说,当所有View的onTouchEvent方法都返回false时,那么Activity的onTouchEvent方法会被调用。
2、Window点击事件的分发过程
接下来看Window是如何将事件传递给ViewGroup的。通过源码可以发现Window是个抽象类,而Window的superDispatchTouchEvent方法也是个抽象方法。因此需要找到Window的实现类才可以。
public abstract boolean superDispatchKeyEvent(KeyEvent event);其实Window的实现类是PhoneWindow,从Window类最上面的注释可以看出来,如下所示,在第二段中,The only existing implementation of this abstract class is android.policy.PhoneWindow。
/** * Abstract base class for a top-level window look and behavior policy. An * instance of this class should be used as the top-level view added to the * window manager. It provides standard UI policies such as a background, title * area, default key processing, etc. * * <p>The only existing implementation of this abstract class is * android.policy.PhoneWindow, which you should instantiate when needing a * Window. Eventually that class will be refactored and a factory method * added for creating Window instances without knowing about a particular * implementation. */
不过PhoneWindow并不在android.policy包下。
实际包名为package com.android.internal.policy.impl;其superDispatchKeyEvent方法源码如下,
PhoneWindow#superDispatchKeyEvent
@Override public boolean superDispatchKeyEvent(KeyEvent event) { return mDecor.superDispatchKeyEvent(event); }
到这里逻辑就很清晰了,PhoneWindow将事件直接传递给了DecorView,这个DecorView是什么呢?请看源码
private final class DecorView extends FrameLayout implements RootViewSurfaceTaker
DecorView是PhoneWindow中一个内部类,在PhoneWindow中有这样一句。
// This is the top-level view of the window, containing the window decor. private DecorView mDecor;
我们知道,通过getWindow().getDecorView()返回的是一个DecorView,而我们通过setContentView设置的View是DecorView的子View,由于DecorView是继承FramLayout而且是View的父元素,所以点击事件一定会传到View。至于怎么传递的,这里就不深究了。这里所里所说的View是通过setContentView设置的View。这个View是顶级View。根View是DecorView。
3、顶级View对点击事件的分发过程
顶级View一般是一个ViewGroup,当点击事件到大顶级ViewGroup后,顶级ViewGroup会调用自己的dispatchTouchEvent方法。一级一级往下分发。回顾上一篇博客(对于一个根ViewGroup来说,点击事件产生后,首先会传递给它,这时它的dispaTouchEvent就会被调用,如果这个ViewGroup的onInterceptTouchEvent方法返回true就表示他要拦截当前事件,接着事件就会交给这个ViewGroup处理,即它的onTouchEvent就会被调用,如果这个ViewGroup的onInterceptTouchEvent方法返回false返回false就表示它不拦截这个事件,这时当前事件会继续传递给它的子元素,接着子元素的dispaTouchEvent方法就会被调用,如此反复直到事件被最终处理。)
首先看ViewGroup对点击事件的分发过程,其主要实现在ViewGroup的dispatchTouchEvent方法中,而这个方法比较长,所以分段说明。先看下面一段。很显然,它描述的是当前View是否拦截点击事情这个逻辑。
<span style="white-space:pre"></span> // 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; }
从上面的代码可以看出,ViewGroup在如下两种情况下会判断是否拦截当前事件:事件类型为down或者mFirstTouchTarget != null。down这个点击事件好理解。那么mFirstTouchTarget != null是什么意思呢。通过后面的代码可以看出来,当ViewGroup不拦截事件并将事件交由子元素处理时,mFirstTouchTarget会被赋值也就是mFirstTouchTarget != null。这样当move事件和up事件到来时,并且事件已经被分发下去,那么onInterceptTouchEvent这个方法将不会再被调用。
当然有一种特殊情况,即使事件已经被分发下去,在move核up事件,onInterceptTouchEvent还是会被调用,那就是FLAG_DISALLOW_INTERCEPT标志位。这个表示为是通过ViewGroup的requestDisallowInterceptTouchEvent这个方法来设置的。即使事件已经分发下去,子元素仍然可以调用父元素的requestDisallowInterceptTouchEvent方法来置位FLAG_DISALLOW_INTERCEPT标志位,从而从父元素判断是否拦截事件。但是down事件除外。因为ViewGroup在分发事件时,如果是down事件就会重置FLAG_DISALLOW_INTERCEPT这个标志位,将导致子View中设置的这个标志位无效。而从上面的代码,也说明了ViewGroup会根据down事件判断是否拦截事件。
// 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(); }
接着再看当ViewGroup不拦截事件的时候,事件会向下分发交由它的子View进行处理,这段源码如下所示。
<span style="white-space:pre"></span> 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; } }
上面这段代码逻辑也很清晰,首先遍历ViewGroup的所有子元素,然后判断子元素是否能够收到点击事件。是否能够收到点击事件主要由两点来衡量:子元素是否在播放动画和点击事件的坐标是否落在子元素的区域内。如果某个子元素满足这两个条件,那么事件就会传递给它处理,dispatchTransformedTouchEvent这个方法实际上就是调用子元素的dispatchTouchEvent方法,在它的内部有如下一段内容,如下所示,由于上面传递child不是null,因此它会直接调用子元素的dispatchTouchEvent方法,这样事件就交由子元素处理,从而完成了一轮事件分发。
if (child == null) { handled = super.dispatchTouchEvent(event); } else { handled = child.dispatchTouchEvent(event); }如果子元素的dispatchTouchEvent返回true,表示子元素已经处理完事件,那么mFirstTouchTarget就会被赋值同时跳出for循环,如下所示:
newTouchTarget = addTouchTarget(child, idBitsToAssign); alreadyDispatchedToNewTouchTarget = true; break;mFirstTouchTarget的赋值在addTouchTarget内部完成,可以看出mFirstTouchTarget是一种单链表结构。这里赋值那么mFirstTouchTarget != null成立。
private TouchTarget addTouchTarget(View child, int pointerIdBits) { TouchTarget target = TouchTarget.obtain(child, pointerIdBits); target.next = mFirstTouchTarget; mFirstTouchTarget = target; return target; }
如果遍历完所有的子元素事件没有被合适处理,有两种情况,
1)ViewGroup没有子元素
2)子元素处理了点击事件,但是dispatchTouchEvent返回false
这是ViewGroup会自己处理点击事件。
在ViewGroup的dispatchTouchEvent方法中,有下面一段代码:
// 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); }
注意这里的第三个参数child为null,那么根据上面的分析,此时会调用handled = super.dispatchTouchEvent(event);
if (child == null) { handled = super.dispatchTouchEvent(event); } else { handled = child.dispatchTouchEvent(event); }
很显然,ViewGroup没有自己处理事件,而是交给了父类,ViewGroup继承自View,这样就转到了View的dispatchTouchEvent方法,即点击事件开始交由View来处理。
4、View对点击事件的分发过程
View对点击事件的处理过程稍微简单一些,注意这里的View不包含ViewGroup。先看它的dispatchTouchEvent方法,如下所示:
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; }
View对点击事件的处理过程就比较简单了,因为View是一个单独的元素,它没有子元素因此无法向下传递事件,所以它只能自己处理事件,所以View的onTouchEvent方法默认返回true。
从上面的源码可以看出View对点击事件的处理过程,首先会判断有没有设置OnTouchListener,如果OnTouchListener中的onTouch方法返回true,那么onTouchEvent方法就不会被调用,可以OnTouchListener的优先级要高于onTouchEvent,这样做的好处是方便子啊外界处理点击点击事件。这也证明上一篇博客中的结论。
接着再分析onTouchEvent的实现,方法内容有点长,先看当View处于不可用状态下点击事件的处理过程。也就方法一开始。不可用状态下还是消耗了点击事件。
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)); }
下面看一下onTouchEvent对点击事件的具体处理,如下所示。
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; }
至此,onTouchEvent方法没有了,可以看出只要CLICKABLE和LONG_CLICKABLE有一个为true,那么它就会消耗这个事件,因为返回了true,这个结果用eclipse很容易看出来,这个博客其实不容易看清楚代码结构,这也证明上一篇博客中的结论。当up事件发生时,会触发performClick方法,
if (mPerformClick == null) { mPerformClick = new PerformClick(); } if (!post(mPerformClick)) { performClick(); }
如果View设置OnClickListener,那么performClick就会调用它的onClick方法。
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; }View的LONG_CLICKABLE属性默认为false,而CLICKABLE属性默认为true,不过具体的View的CLICKABLE又不一定,确切来说是可点击的View其CLICKABLE属性true,比如Botton,不可点击的View的CLICKABLE为false,比如TextView。。通过setClickable和setLongClickable可以设置这两个属性。另外setOnClickListener和setOnLongClickListener会自动将View的这两个属性设为true。这一点从源码可以看出来。
public void setOnClickListener(OnClickListener l) { if (!isClickable()) { setClickable(true); } getListenerInfo().mOnClickListener = l; }
public void setOnLongClickListener(OnLongClickListener l) { if (!isLongClickable()) { setLongClickable(true); } getListenerInfo().mOnLongClickListener = l; }
最后总结一下,这篇博客主要从源码角度分析View的事件分发机制。一般过程如下。
Activity——>PhoneWindow——>DecorView——>ViewGroup——>View
- View的事件分发机制源码解析
- Android View 事件分发机制 源码解析
- Android View 事件分发机制 源码解析
- Android View 事件分发机制 源码解析
- Android View 事件分发机制 源码解析
- Android View 事件分发机制 源码解析
- Android View 事件分发机制 源码解析
- Android View 事件分发机制 源码解析
- Android View 事件分发机制 源码解析
- Android View 事件分发机制 源码解析
- Android 源码解析View的touch事件分发机制
- Android事件分发机制源码解析(一)-View的事件分发机制
- 源码分析View的事件分发机制
- View的事件分发机制源码分析
- Android View 事件分发机制 源码解析(View篇)
- View的事件分发机制解析
- Android 事件分发机制解析之View的事件分发
- android View的事件分发源码解析
- HttpClient 4.3教程(转载)
- eclipse打断点调试进入到class文件中--解决方法
- Java编程思想18.1 - 字节流和字符流
- 1、Android测试入门
- structs2 运行流程分析
- View的事件分发机制源码解析
- Eclipse Download and Installation (for Python) Instructions
- css小技巧
- 暗时间理论
- Unity Shader Example 3 (GrabPass捕捉屏幕纹理 )
- Android基础之ontouch事件没有up解决方法
- HDOJ_Tempter of the Bone
- 实现javascript Date加减功能
- Authid Current_User is解决执行过程中01031权限不足的问题