[android 自定义控件](2)事件传递


写这篇文章有两个目的:

  1. 从源头理解消息传递以方便自定义控件。
    再次希望你知道Acitvitiy ,Window 和 DecorView的关系,如果不知道可以看android 自定义控件:(1) ContentView和inflater.不想看也可以。下面我也会做尖端的介绍。
  2. 做好总结以后就不用一遍一遍看教程回忆了

Activity中的事件传递

为了更好的学习,我们先要对下面知识达成共识。如果要深入探究为什么这将是一个浩大的工程。

  1. android 的和点击屏幕相关的事件是一个类名字叫做MotionEvent ,和键盘相关的叫做KeyEvent。
  2. android 底层会把事件传递给Activity的dispatchTouchEvent函数。
  3. 当你在屏幕上操作时,就会有一堆连续的事件被传递给dispatchTouchEvent函数。这些事件的顺序如下MotionEvent.ACTION_DOWN − − > --> >ACTION_MOVE… − − > --> >ACTION_UP。

废话不多说,我们来看Activity中的dispatchTouchEvent函数源码

    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
		     
            onUserInteraction();
            //这是一个空方法,所以想在Activity中监听点击事件可以实现这个函数
        }
        //下面是关键代码
        if (getWindow().superDispatchTouchEvent(ev)) {
	        
            return true;
        }
        return onTouchEvent(ev);
    }

2.1

现在我们来看看getWindow的源代码


  public Window getWindow() {
        return mWindow;
    }

mwindow是什么呢

  private Window mWindow;

可以看见mwindow是一个Window类的变量,那么他在哪赋值的呢?最终我们在Acitivity的attach方法中找到了赋值的地方

mWindow = new PhoneWindow(this, window);

现在我们可以看见 使用的是一种组合模式,mwindows 其实是Window 的子类PhoneWindow。现在我们可以看看它的superDispatchTouchEvent方法了

 @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }

mDecor是DecorView类的实例,是程序的根View

public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks 

好了我们接着看DecorView中的superDispatchTouchEvent

  public boolean superDispatchTouchEvent(MotionEvent event) {
            return super.dispatchTouchEvent(event);
        }

调用起父类GroupLayout中dispatchTouchEvent函数,这样就跳到了根View的dispatchTouchEvent
函数

 public boolean dispatchTouchEvent(MotionEvent ev) {
//下面讲
    }

好了回到之前dispatchTouchEvent的代码 ( 2.1 ) (2.1) (2.1),我们看看onTouchEvent的代码

public boolean onTouchEvent(MotionEvent event) {
        if (mWindow.shouldCloseOnTouch(this, event)) {
        //如果点击的地方应该关闭,那么就关闭Activity,正常情况是没有这个点击区域的
            finish();
            return true;
        }

        return false;
    }

Activity传递消息总结:

  1. 只有事件为 MotionEvent.ACTION_DOWN时,Activity会运行 onUserInteraction()方法,
  2. 如果根View的dispatchTouchEvent函数返回true,说明事件被子View处理,不需要执行Activity的onTouchEvent函数来处理,activity的dispatchTouchEvent返回true
  3. 如果ViewGroup的dispatchTouchEvent函数返回False。说明子View没有处理事件,需要调用Activity的onTouchEvent函数来处理,事件被onTouchEvent处理就返回true,没被onTouchEvent处理就false
  4. activity的dispatchTouchEvent的返回值没什么用

Tips:

因为phoneWindow是Internal API所以我们正常情况下在ide开发环境中是看不见的。

  • 你可以在sdk下source目录下的包路径package com.android.internal.policy.impl;可是此文件下的phoneWindow没有代码缩进没法观看。
  • 去AOSP项目上找源代码
  • 使用CTRL+SHIFT+R

ViewGroup 中的事件传递

当Activity接受到事件之后,会传递给根View的dispatchTouchEvent函数,如果此函数返回true那么就不调用Activity的onTouchEvent函数。现在我们来看ViewGroup中的源代码吧。(?真长,看着眼睛都疼)

 @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {


	 //.........................
		//设置函数返回值为false;
        boolean handled = false;
        //过滤事件以满足安全政策的需要
        if (onFilterTouchEventForSecurity(ev)) {
            final int action = ev.getAction();
            final int actionMasked = action & MotionEvent.ACTION_MASK;
            // Handle an initial down.
            //核心代码1:
            // 
            //
            //down事件发生时,android 会记录那个view能处理这个事件,这样之后所有事件就会直接传递给这个view,提高性能。
            //因为MotionEvent.ACTION_DOWN是一切动作的开端,所以down事件德时候,把所有状态归位,相应事件的View容器mFirstTouchTarget变成null
            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.
                //翻译:
        		//当开始一个新手势之前抛弃所有之前状态
        		//由于app的切换,ANR,或其他状态的改变,框架可能已经抛弃之前的up和cancel手势
        		//
        		
//清除以往的Touch状态然后开始新的手势,cancelAndClearTouchTargets(ev)方法干了一件大事就是设置mFirstTouchTarget(单链表结构)设置为了null,
//mFirstTouchTarget是存储接受down事件的View的一个链表,以方便后面的消息能直接通过mFirstTouchTarget传递给View,节省了每次查询的操作来优化性能
                cancelAndClearTouchTargets(ev);

//resetTouchState()方法很重要他会重置FLAG_DISALLOW_INTERCEPT标志,
//从下面的代码你可以看出,他会间接控制拦截intercepted。所以无论什么时候,只要出现ACTION_DOWN事件onInterceptTouchEvent方法都会被调用*/
                resetTouchState();
            }
            
            // Check for interception.
            //核心代码2:
            //
            //
            //通过控制这个拦截变量,我们可以很方便的控制mFirstTouchTarget的初始化
            final boolean intercepted;
//记住这里的intercepted设置的触发条件,通过阅读后面的代码,我们回过头会发现,
//down事件会触发初始化mFirstTouchTarget,这样之后非down的事件会因为mFirstTouchTarget !=null而进入下面的if判断

            if (actionMasked == MotionEvent.ACTION_DOWN
                    || mFirstTouchTarget != null) {

                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
                //disallowIntercept 默认为false
                //ViewGroup中提供了public的requestDisallowInterceptTouchEvent方法来设置FLAG_DISALLOW_INTERCEPT标志,这样间接就设置了disallowIntercept变量
                
                if (!disallowIntercept) {
                  // 如果ACTION_DOWN时无View处理的话,mFirstTouchTarget无法被赋值,所以onInterceptTouchEvent就会被之调用一次
                    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.
                //ACTION_DOWN的点没有处理事件View的话,之后的move和up事件都会被拦截。
                intercepted = true;
            }
            //在这小总结一下,默认情况下事件时不会被拦截的,也就是intercepted ==false。
            //想要人为设置拦截(intercepted ==true)的方法只有一个,那就是重写onInterceptTouchEvent,然后让他返回true。如果想要人为强制不拦截也就是intercepted ==false,(不推荐)
            //可以调用requestDisallowInterceptTouchEvent方法把disallowIntercept==true。intercepted和FLAG_DISALLOW_INTERCEPT 两者控制着拦截操作
       
            
            // If intercepted, start normal event dispatch. Also if there is already
            // a view that is handling the gesture, do normal event dispatch.
     		//如果已经拦截,开始一个正常的消息传递
     		//或者有一个View正在处理手势,也开始正常的事件传递
            if (intercepted || mFirstTouchTarget != null) {
                ev.setTargetAccessibilityFocus(false);
            }

            // Check for cancelation.
           // 人为操作产生不了Cancel行为。系统内部的操作,跳过。
            final boolean canceled = resetCancelNextUpFlag(this)
                    || actionMasked == MotionEvent.ACTION_CANCEL;


            // Update list of touch targets for pointer down, if needed.
            //下面寻是寻找能接受事件的View的代码
            //split是否把事件向子view传递的标志(默认为true)
            // ViewGroup方法setMotionEventSplittingEnabled负责设置FLAG_SPLIT_MOTION_EVENTS标志来间接控制split
            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
            
			 //newTouchTarget 和mFirstTouchTarget同一个类型的,做临时存储用的
            TouchTarget newTouchTarget = null;
            //alreadyDispatchedToNewTouchTarget 这个标志后面会用到,默认为false
            boolean alreadyDispatchedToNewTouchTarget = false;
            
		//核心代码3:
		//
		//
		//下面的代码是寻找能处理down事件的子View,找到了就会初始化mFirstTouchTarget。
		//如果down事件的时候设置了拦截,会跳过下面的代码,这样mFirstTouchTarget就无法初始化
		//之后的的intercepted就会一直是true
            if (!canceled && !intercepted) {
                // If the event is targeting accessiiblity focus we give it to the
                // view that has accessibility focus and if it does not handle it
                // we clear the flag and dispatch the event to all children as usual.
                // We are looking up the accessibility focused host to avoid keeping
                // state since these events are very rare.
//若果事件是accessiiblity focus ,且目标不处理这个事件,我们清楚标志,传递给他的子View让他们处理。
//我们正在查找accessibility focused 的宿主,以避免保持保持状态,因为这些事件很罕见
                View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
                        ? findChildWithAccessibilityFocus() : null;
//ACTION_DOWN点有子View能处理的话,即dispatchTOuchEvent返回True时。该View会被添加到mFirstTouchTarget中。
//这样,之后的up和Move就直接根据mFirstTouchTarget来传递了
                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) {
                    //寻找View,子View的数目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.
                        /*获得子View的数组*/
                        final ArrayList<View> preorderedList = buildTouchDispatchChildList();
                        final boolean customOrder = preorderedList == null
						//下面代码会寻找接受事件的子View
                        final View[] children = mChildren;
                        //倒叙遍历子View,这也解释了为什么后添加的在上面,且先接受到消息
                        for (int i = childrenCount - 1; i >= 0; i--) {
                            final int childIndex = getAndVerifyPreorderedIndex(
                                    childrenCount, i, customOrder);
                            final View child = getAndVerifyPreorderedView(
                                    preorderedList, children, childIndex);

                            // If there is a view that has accessibility focus we want it
                            // to get the event first and if not handled we will perform a
                            // normal dispatch. We may do a double iteration but this is
                            // safer given the timeframe.
                            //下面是做一些查找的优化
                            if (childWithAccessibilityFocus != null) {
                                if (childWithAccessibilityFocus != child) {
                                    continue;
                                }
                                childWithAccessibilityFocus = null;
                                i = childrenCount - 1;
                            }
 					  			//动画是否在播放,点击点是否在子View的范围内
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                 
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }
							//通过getTouchTarget查找child是否在mFirstTouchTarget.next这条target链中的某一个targe中,
							//如果在则返回这个target,否则返回null,为什么会有这句话呢?
							//他是为了拦截消息考虑的,当我们在非down的事件下设置拦截时,又不在之后的消息设置非拦截时,可以省去重新遍历寻找的事件
                            newTouchTarget = getTouchTarget(child);
           // move 和up事件会直接跳到这,从这开始运行。
                            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;
                            }
							//如果在mFirstTouchTarget中找不到,那么做一些标记清除工作
                            resetCancelNextUpFlag(child);
                            
                         //下面这个方法,就是寻找接受消息的子View的核心方法了负责向子view分发事件
                         //   //该方法十分重要,在该方法为一个递归调用,会递归调用dispatchTouchEvent()方法。

                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {      
                                // Child wants to receive touch within its bounds.
                                mLastTouchDownTime = ev.getDownTime();
                                if (preorderedList != null) {
                                    // childIndex points into presorted list, find original index
                                    for (int j = 0; j < childrenCount; j++) {
                                        if (children[childIndex] == mChildren[j]) {
                                            mLastTouchDownIndex = j;
                                            break;
                                        }
                                    }
                                } else {
                                    mLastTouchDownIndex = childIndex;
                                }
                                mLastTouchDownX = ev.getX();
                                mLastTouchDownY = ev.getY();
                                //把找到的接受消息的Child 添加到mFirstTouchTarget链中,并且给newTouchTarget这条新链
                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
                                //设置标记为true,表示新mFirstTouchTarget链构造完成,同时也表示down事件被子View处理了。
                                alreadyDispatchedToNewTouchTarget = true;
                                break;
                            }

                            // The accessibility focus didn't handle the event, so clear
                            // the flag and do a normal dispatch to all children.
                            ev.setTargetAccessibilityFocus(false);
                        }
                        if (preorderedList != null) preorderedList.clear();
                    }

                    if (newTouchTarget == null && mFirstTouchTarget != null) {
                        // Did not find a child to receive the event
                        // Assign the pointer to the least recently added target.
                        /*该if表示在事件传递过程中(down->move->...->up)中每次时newTouchTarget指向mFirstTouchTarget的尾部*/
                        newTouchTarget = mFirstTouchTarget;
                        while (newTouchTarget.next != null) {
                            newTouchTarget = newTouchTarget.next;
                        }
                        newTouchTarget.pointerIdBits |= idBitsToAssign;
                    }
                }
            }
            ///在这总结一下:
            //ViewGroup循环寻找能接受事件的子View的方法是dispatchTransformedTouchEvent。
            //如果子View找到了,且愿意消费该事件(dispatchTouchEvent返回true),那么mFirstTouchTarget为!=null,否者为mFirstTouchTarget为==null
			

//核心代码4: 
//
//
//经过down事件时的mFirstTouchTarget初始化,可能找到了处理down的子view,也可能没找到,所以mFirstTouchTarget可能时null或者!null
//后续的move和up就会直接跳到这开始运行。
            // Dispatch to touch targets.
            if (mFirstTouchTarget == null) {
            //dispatchTransformedTouchEvent的第三个参数是null,
            //表示直接调用super.dispatchTouchEvent处理事件ViewGroup的父类是View,这时候就会像普通的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;
               //mFirstTouchTarget!=null 说明View愿意接受事件,
               //至此事件就会直接传递给mFirstTouchTarget 链中的View,这样就不用再运行核心代码3的内容了                              
                while (target != null) {
//target 就是mFirstTouchTarget ,它会在每次为其中的View传递事件后“-1”,最终跳出循环
                    final TouchTarget next = target.next;
                    //
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                    //上面说了newTouchTarget指向mFirstTouchTarget的尾部也就是target,所以这个if表示事件分发完了就返回true
                        handled = true;
                    } else {
                    //核心代码5
                    //
                    //
                    //intercepted如果是ture,cancelChild 一定就是true
                    cancelChild==true时,会向子View发送MotionEvent.ACTION_CANCEL事件,如果为false,消息会被正常发送给子View
                       
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                       
                        if (dispatchTransformedTouchEvent(ev, cancelChild,
                                target.child, target.pointerIdBits)) {
                                /*还是使用dispatchTransformedTouchEvent来递归传递事件 */
                            handled = true;
                        }
                        //核心代码6:
                        //
                        //
                        //下面代码会使拦截发生时让mFirstTouchTarget=null,不然我们设不设置拦截都一样
                        if (cancelChild) {
                        //前面说了cancelChild和intercepted值有关,所以进入这个if块时,
                        //target( 和mFirstTouchTarget 同样的东西)!=null,不然就不会进来。且intercepted的,
                        //这个意思就是我们想在事件传递的过程中(down->move->..->up)非dwon情况下突然来一个调用onInterceptTouchEvent返回方法true
                        
                       //下面的会代码会让mFirstTouchTarget==null,这样下次进来的时候就会进入mFirstTouchTarget==null的语句块中了
                            if (predecessor == null) {
                                mFirstTouchTarget = next;
                            } else {
                                predecessor.next = next;
                            }
                          、
                            target.recycle();
                            target = next;
                            continue;
                        }
                    }
                    //它保持者现在的child,也就是刚传进消息的child
                    predecessor = target;
                   //“-1”操作,指向下一个
                    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);
            }
        }

       //..........................
        return handled;
    }

好了,看完上面的源码之后,事件的核心就落在dispatchTransformedTouchEvent函数上面了。

    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
            View child, int desiredPointerIdBits) {
        final boolean handled;//下面是核心代码

//下面代码当事件会当cancel参数为true时(一种过滤手段)为所有的子View发送MotionEvent.ACTION_CANCEL(3)
   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;
        }
        ……
        //下面时普通的事件传递
   if (child == null) {
    //当没有子View时,调用ViewGroup的父类,也就是View的dispatchTouchEvent函数来分发事件了
            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());
            }
//否者调用调用child的dispatchTouchEvent
            handled = child.dispatchTouchEvent(transformedEvent);
        }
	/*这时候如果子child时View,那么和上面一样调用View的dispatchTouchEvent,如果child时ViewGroup那么,就产生了递归调用的情况,事件就可以被分发出去了*/
        // Done.
        transformedEvent.recycle();
            //看见下面的返回值了吗,它的取值完全依赖于子View/ViewGroup的的dispatchTouchEvent
        return handled;
    }

ViewGroup传递消息总结

我们来总结总结:

  1. ViewGroup在出现down事件的时候会把处理此事件的子View(View的dispatchTouchEvent返回true)保存在一mFirstTouchTarget中(多个子View重叠在一起,也会添加到这个链表中)。后续的Move和up事件传递到这个链表中的View中

  2. onInterceptTouchEvent 表示是否拦截事件(默认返回false,不拦截)。如果拦截的话,down事件时不会去找子View,mFirstTouchTarget也就会被初始化为null,这样就会调用ViewGroup的父类(View)的dispatchTouchEvent函数来处理down事件,之后的move和up事件就会因为mFirstTouchTarget为null,而把intercepted拦截参数设置成true,不会去调用onInterceptTouchEvent函数。之后所有事件就只会传递到ViewGoup的父类View的dispatchTouchEvent函数中/

  3. onInterceptTouchEvent 不拦截的话,down事件时会去找子View来处理down事件,如果找到就添加到mFirstTouchTarget中,这样mFirstTouchTarget就不会为null,之后每一个move和up事件都会调用onInterceptTouchEvent函数。
    3.1. 如果此时onInterceptTouchEvent返回的都是false的话,这样所有事件都是传递到mFirstTouchTarget存储的View的dispatchTouchEvent函数中,且mFirstTouchTarget会被清空=null。
    3.2. 如果此时onInterceptTouchEvent返回的时true的话,cancel事件会被传递到mFirstTouchTarget的View的dispatchTouchEvent函数中

  4. onInterceptTouchEvent 不拦截且找不到VIew来处理down的话,这时候mFirstTouchTarget会被初始化为null,这样就会调用ViewGroup的父类(View)的dispatchTouchEvent函数来处理down事件,之后的move和up事件就会因为mFirstTouchTarget为null,而把intercepted拦截参数设置成true,不会去调用onInterceptTouchEvent函数。之后所有事件就只会传递到ViewGoup的父类View的dispatchTouchEvent函数中/

  5. 在事件传递(MotionEvent.ACTION_DOWN->ACTION_MOVE…->ACTION_UP)传递的过程中设置onInterceptTouchEvent来完成拦截。

View中的事件传递

    public boolean dispatchTouchEvent(MotionEvent event) {
        // If the event should be handled by accessibility focus first.

        if (event.isTargetAccessibilityFocus()) {
            // We don't have focus or no virtual descendant has it, do not handle the event.
     
            if (!isAccessibilityFocusedViewOrHost()) {
                return false;
            }
            // We have focus and got the event, then use normal event dispatch.
     
            event.setTargetAccessibilityFocus(false);
        }
//这个result变量就是函数最后返回的变量,现在为false
        boolean result = false;

        if (mInputEventConsistencyVerifier != null) {
	      
            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
        }

        final int actionMasked = event.getActionMasked();
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            // Defensive cleanup for new gesture
            stopNestedScroll();
        }
	//前面都是设置一些标记和处理input与手势等传递,这些我们不关心
        if (onFilterTouchEventForSecurity(event)) {//判断当前View是否没被遮住等
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
        
            ListenerInfo li = mListenerInfo;
              //ListenerInfo是View的静态内部类,用来定义一堆关于View的XXXListener等方法
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
             /*@1:判断View是否添加过监听(setOnTouchListener),View是否是ENABLED,所有View默认为ENABLED,如果前两项都ok再看ontouch的返回值*/
             
                result = true;
                
            }
//上面的if不满足就调用ontouchevent函数
            if (!result && onTouchEvent(event)) {
            //如果result为false(没有添加监听或View不是ENABLED或onTouch返回为false)时,运行onTouchEvent
                result = true;
            }
        }
        
		//下面时一些收尾清除工作,可以跳过
        if (!result && mInputEventConsistencyVerifier != null) {
            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
        }

        // Clean up after nested scrolls if this is the end of a gesture;
        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
        // of the gesture.
        if (actionMasked == MotionEvent.ACTION_UP ||
                actionMasked == MotionEvent.ACTION_CANCEL ||
                (actionMasked == MotionEvent.ACTION_DOWN && !result)) {
            stopNestedScroll();
        }
        
		//如果返回false 之后的事件动作就不会在传递了
        return result;
        
    }

上面的关键代码就是:

            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;           
            }

li!=null显然不可能。li.mOnTouchListener 在哪赋值的呢?

   public void setOnTouchListener(OnTouchListener l) {
        getListenerInfo().mOnTouchListener = l
    }

所以只要View调用了setOnTouchListener(添加监听)就会被赋值。

总结:

  1. 注册touch监听,控件为enable状态,ontouch函数返回true,三者都满足dispatchTouchEvent返回true。否则调用onTouchEvent
  2. onTouchEvent中会调用onclick函数,如果事件被处理,onTouchEvent会返回true,反之false。
  3. view是clickable的话onTouchEvent才能返回true,否则只能返回false

OnTouchEvent

OnTouchEvent函数调用发生在View没有添加OnTouchListener监听或View不是ENABLE,或OnTouchListener.onTouch函数返回false是被调用

    public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            if (action == 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)
                    || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
        }
        //从上面可以看出,如果View是DISABLED,那么如下讨论 如果View是CLICKABLE ,onTouchEvent的true,反之是DisCLICKABLE,onTouchEvent的false
        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }
		//通过上面筛选,现在View只可能是ENABLE的,所以先看View是不是CLICKABLE
        if (((viewFlags & CLICKABLE) == CLICKABLE ||
                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
             //进入这里时表示View时ENABLE且是CLICKABLE,这就是我们想要的状态,现在我们再来判断是什么点击事件把
      
            switch (action) {
                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, x, y);
                       }
					//然后判断如果不是longPressed
                        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
                            // 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 中的语句很关键
                                if (mPerformClick == null) {
                                //PerformClick是一个Runnable
                                    mPerformClick = new PerformClick();
                                }
                                //@1:通过post在UI Thread中执行一个PerformClick的Runnable,
                                if (!post(mPerformClick)) {
							    //如果UI线程不接受,就自己执行
                                    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();
                    }
                    mIgnoreNextUpEvent = false;
                    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();
                        }
                        mPendingCheckForTap.x = event.getX();
                        mPendingCheckForTap.y = event.getY();
                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    } else {
                        // Not inside a scrolling container, so show the feedback right away
                        setPressed(true, x, y);
                        checkForLongClick(0, x, y);
                    }
                    break;

                case MotionEvent.ACTION_CANCEL:
                    setPressed(false);
                    removeTapCallback();
                    removeLongPressCallback();
                    mInContextButtonPress = false;
                    mHasPerformedLongPress = false;
                    mIgnoreNextUpEvent = false;
                    break;

                case MotionEvent.ACTION_MOVE:
                    drawableHotspotChanged(x, y);

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

//通过上面筛选现在View是DISCLICKABLE,返回false
        return false;
    }

来看看 PerformClick 类。

 private final class PerformClick implements Runnable {
        @Override
        public void run() {
            performClick();
        }
    }

那我们来看看performClick。

 public boolean performClick() {
        final boolean result;
        final ListenerInfo li = mListenerInfo;
        
        if (li != null && li.mOnClickListener != null) {
        //和之前的差不多,检测View是不是添加了OnClickListener监听
            playSoundEffect(SoundEffectConstants.CLICK);
            //执行OnClickListener.onClick函数
            li.mOnClickListener.onClick(this);
            result = true;
        } else {
            result = false;
        }

        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
        return result;
    }

View消息传递总结:

  1. View是Enable,且添加了touch监听,onTouch函数返回true,三者成立说明事件被处理,不用调用onTouchEvent。dispatchEvent返回true,事件不用传递了
  2. 否则调用onTouchEvent来处理事件,这个返回true说明事件被处理,onclick函数就是在其中内调用的,dispatchEvent返回true说明事件被处理不用传递了
  3. view的dispatchEvent返回True表示事件被处理,不需要父View们来处理,反之需要父View的super.dispatchevent来处理,注意重写onTouch和onThouchEvent
  4. onTouchEvent 处理cancel事件返回true
  5. view必须时clickable,onTouchEvent才能返回true

我自己写了些案例方便巩固知识点[android 自定义控件](3)事件传递的一些案例思考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值