Android高级UI篇,事件分发机制及冲突的原因与解决方案

先抛出几个问题,带着问题思考

1、onTouch与onClick之间会产生事件的冲突吗?
2、事件在控件中是如何传递的?
3、事件冲突产生的根本原因是什么?
4、如何解决事件冲突?

先看一段代码

 btn_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "onClick");
            }
        });

        btn_click.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.e(TAG, "onTouch: " + event.getAction());

                return ture;
            }
        });

上述代码,如果setOnTouchListener中返回true,onClick中是否会有打印?答案是否定的,或许从有模糊的意识知道这样的结果,为清晰思路,还是要从源码分析验证:

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

            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

如上View的dispatchTouchEvent方法,虽然dispatchTouchEvent一般是分发逻辑,在view中,dispatchTouchEvent就是用来处理事件,在mOnTouchListener.onTouch中如果返回true,后面result会赋值为true,对应的影响到 ==if (!result && onTouchEvent(event))==中onTouchEvent方法不会执行,进而onClick方法不会执行;

事件在控件中是如何传递的

Android高级UI篇,事件分发机制及冲突的原因与解决方案_第1张图片
经典配图:Activity -> phoneWindow ->DecorView -> ViewGroup -> View,即DecorView 本身是frameLayout,也是一个ViewGroup,所以我们关心就是从ViewGroup到view这一部分的分发过程,先抛出一个结论:ViewGroup,先要走分发流程,再走处理流程View,只能走处理流程,ViewGroup中没有重写onTouchEvent方法,view中虽然有dispatchTouchEvent,但是用来处理事件的。

ViewGroup的dispatchTouchEvent方法,做了什么???

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

 public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
                && ev.getAction() == MotionEvent.ACTION_DOWN
                && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
                && isOnScrollbarThumb(ev.getX(), ev.getY())) {
            return true;
        }
        return false;
    }

以上对ViewGroup分为拦截和不拦截两种情况分析(down事件)

ViewGroup如果拦截(如下拦截方法,原生的99%情况下是不拦截,所以一般会自己重写ViewGroup onInterceptTouchEvent方法),onInterceptTouchEvent 返回true,往下走,跨过分发流程,到处理流程:

    //自己一般重写
    public boolean onInterceptTouchEvent(MotionEvent event) {
        //内部拦截。加上这步,即down事件不去拦截
        if (event.getAction() == MotionEvent.ACTION_DOWN){
            super.onInterceptTouchEvent(event);
            return false;
        }
        return true;
    }

// 源码中的拦截方法
  public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
                && ev.getAction() == MotionEvent.ACTION_DOWN
                && ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
                && isOnScrollbarThumb(ev.getX(), ev.getY())) {
            return true;
        }
        return false;
    }
    

            // 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 {
            


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

如上代码片段,在确定接受事件view前,mFirstTouchTarget 为null,进入到dispatchTransformedTouchEvent,第三个参数child为null,最终走到child.dispatchTouchEvent(event);即VeiwGroup即使拦截了事件,最终还是交给到View去处理事件。

ViewGroup不拦截(disallowIntercept 子控件没有通过requestDisallowInterceptTouchEvent设置情况下,为false),onInterceptTouchEvent返回值intercepted 为false,则将往下分发流程

   for (int i = childrenCount - 1; i >= 0; i--) {
       // 、、、、、、、、
		  if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
		                                // Child wants to receive touch within its bounds.
		                                //进入到这里,说明已经确定了接收事件的字View,到break跳出for循环
		                                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();
		                                //addTouchTarget 最终mFirstTouchTarget将不再为null
		                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
		                                // alreadyDispatchedToNewTouchTarget 置为空
		                                alreadyDispatchedToNewTouchTarget = true;
		                                break;
		                            }
                            
                            // 、、、、、、、、
}

        
		private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
		            View child, int desiredPointerIdBits) {
		        final boolean handled;
		
		        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);
		                    // 调用到veiw的dispatchTouchEvent方法,并返回最终的执行结果
		                    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);
		        }
          //
		  private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
		        final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
		        // mFirstTouchTarget此刻为null,此时 target.next将置为null
		        target.next = mFirstTouchTarget;
		        mFirstTouchTarget = target;
		        // 到此 target.next 为空,mFirstTouchTarget 复制target,不在为空
		        return target;
		    }

如上代码,在for循环中便利,寻找符合条件的字view去接受事件,最终跳出for便利循环,即分发流程结束,往下走看处理流程,理论上找到接收事件的子View,事件就交友子View处理,viewGroup将不再处理,看看源码怎么处理的

   if (mFirstTouchTarget == null) {
                // No touch targets so treat this as an ordinary view.
                //到这,如果没有子view接收事件,则Viewgroup自己处理,相当于自己拦截
                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) {
                          //经上分析 target.next为空,next将置为空
                    final TouchTarget next = target.next;
                    //经上分析,此时alreadyDispatchedToNewTouchTarget 已置为了true, newTouchTarget 即为mFirstTouchTarget
                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                     //直接进入if ,将handled置为true
                        handled = true;
                    } else {                     
                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
                                || intercepted;
                         //move事件来之后,走这里,,即直接走到view分发,让view去处理,此时while循环                   仍然只走一次       
                        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将置空,即while循环只会执行一次,做的工作只是将handled置为空,之后事件交由子view处理
                    target = next;

经上分析,Viewgroup找到接收事件的子View,事件就交友子View处理,viewGroup将不再处理事件,只是将handled 置为true,意为事件已经得到了处理。
如果子view都不处理事件,走dispatchTransformedTouchEvent(ev, canceled, null ,TouchTarget.ALL_POINTER_IDS);相当于自己处理,自己拦截

move事件分析

经上down事件已确定了接收事件的子view,move事件来时,也是先经由ViewGroup,先进行分发,然后再进行处理逻辑,如下,因不满足分发条件,将不再走分发逻辑,直接走处理逻辑。

           if (actionMasked == MotionEvent.ACTION_DOWN
                      || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
                      || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {

如上代码注释,move事件来之后,即直接走到view分发,让view去处理,此时while循环仍然只走一次 ,至此,down事件和move事件分析完毕。

事件冲突

什么是事件冲突,说白了就是事件只有一个,但多个view想要,最后处理的对象不是我们想要的对象,就发生了冲突。对于事件冲突的解决,只能通过move事件拦截,在move事件中处理。

事件冲突处理方案-- 内部拦截与外部拦截法,闪亮登场

内部拦截法:由子view去处理冲突,因为父控件onInterceptTouchEvent方法返回了true,子view无法拿到事件,这时候子view需要借助requestDisallowInterceptTouchEvent方法,去改变mGroupFlag的值,

   protected static final int FLAG_DISALLOW_INTERCEPT = 0x80000;
    @Override
    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
            // We're already in this state, assume our ancestors are too
            return;
        }

        if (disallowIntercept) {
            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
        } else {
            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        }

        // Pass it up to our parent
        if (mParent != null) {
            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
        }
    }
///
    final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;

如上代码
mGroupFlags |= FLAG_DISALLOW_INTERCEPT & FLAG_DISALLOW_INTERCEPT 一定 >0
mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT & FLAG_DISALLOW_INTERCEPT 一定等于0;
即当调用 requestDisallowInterceptTouchEvent(false)时,disallowIntercept 为true,此时ViewGroup不走拦截方法,相反requestDisallowInterceptTouchEvent(true),disallowIntercept 为false,即通知ViewGroup可以拦截,执行拦截方法。
以viewPager嵌套listView为例,在move方法中,通知父控件可以进行拦截,我们分析这里的逻辑:

  @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                getParent().requestDisallowInterceptTouchEvent(true);
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                int deltaX = x - mLastX;
                int deltaY = y - mLastY;
                if (Math.abs(deltaX) > Math.abs(deltaY)) {
                    getParent().requestDisallowInterceptTouchEvent(false);
                }
                break;
            }
            case MotionEvent.ACTION_UP: {
                break;

            }
            default:
                break;
        }

        mLastX = x;
        mLastY = y;
        return super.dispatchTouchEvent(event);
    }

在通知父控件拦截事件后,拦截变量intercepted为true,继续下面的事件处理流程:

	     while (target != null) {
	                final TouchTarget next = target.next;
	                //alreadyDispatchedToNewTouchTarget已重新置为了false, 
	                if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
	                    handled = true;
	                } else {
	                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
	                            || intercepted;
	                      //此处intercepted为true,所以cancelChild 为true,
	                    if (dispatchTransformedTouchEvent(ev, cancelChild,
	                            target.child, target.pointerIdBits)) {
	                        handled = true;
	                    }


	  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) {
	        //此处传过来的cancel为true,即会将事件置为cancel,即得到开篇时结论,当事件被父控件抢走时,子控件是执行cancel事件
	            event.setAction(MotionEvent.ACTION_CANCEL);
	            if (child == null) {
	                handled = super.dispatchTouchEvent(event);
	            } else {
	   
	                handled = child.dispatchTouchEvent(event);
	            }
	            event.setAction(oldAction);
	            return handled;
	        }

外部拦截法。即直接由父容器去决定,事件是否拦截,同样以viewPager嵌套listView为例,在viewPager中重写onInterceptTouchEvent方法,事实上,目前viewPager嵌套listView可以不做任何的处理,也不会出现滑动冲突,因为现在这块Google有帮我们处理了,在viewPager源码中可以看到有相关的处理。

		public boolean onInterceptTouchEvent(MotionEvent event) {
		
		        //以下为外部拦截
		        int x = (int) event.getX();
		        int y = (int) event.getY();
		
		        switch (event.getAction()) {
		            case MotionEvent.ACTION_DOWN: {
		                mLastX = (int) event.getX();
		                mLastY = (int) event.getY();
		                break;
		            }
		            case MotionEvent.ACTION_MOVE: {
		                int deltaX = x - mLastX;
		                int deltaY = y - mLastY;
		                if (Math.abs(deltaX) > Math.abs(deltaY)) {
		                    return true;
		                }
		                break;
		            }
		            case MotionEvent.ACTION_UP: {
		                break;
		            }
		            default:
		                break;
		        }
		
		//        通过返回true或者false 进行拦截 返回super.onInterceptTouchEvent(event)没问题 
		        return super.onInterceptTouchEvent(event);
		
		    }

分析到此,理解尚浅,欢迎大家一起讨论学习

你可能感兴趣的:(android,ui,java)