android的touch事件详解

来源:互联网 发布:软件测评师报名 编辑:程序博客网 时间:2024/04/28 09:35

我们用手指去触摸Android手机屏幕,就会产生一个触摸事件,但是这个触摸事件在底层是怎么分发的呢?这个我还真不知道,这里涉及到操作硬件(手机屏幕)方面的知识,也就是Linux内核方面的知识,我也没有了解过这方面的东西,所以我们可能就往上层来分析分析,我们知道Android中负责与用户交互,与用户操作紧密相关的四大组件之一是Activity, 所以我们有理由相信Activity中存在分发事件的方法,这个方法就是dispatchTouchEvent(),我们先看其源码吧

public boolean dispatchTouchEvent(MotionEvent ev) {         //如果是按下状态就调用onUserInteraction()方法,onUserInteraction()方法        //是个空的方法, 我们直接跳过这里看下面的实现        if (ev.getAction() == MotionEvent.ACTION_DOWN) {            onUserInteraction();        }                 if (getWindow().superDispatchTouchEvent(ev)) {            return true;        }                 //getWindow().superDispatchTouchEvent(ev)返回false,这个事件就交给Activity        //来处理, Activity的onTouchEvent()方法直接返回了false        return onTouchEvent(ev);    }
这个方法中我们还是比较关心getWindow()的superDispatchTouchEvent()方法,getWindow()返回当前Activity的顶层窗口Window对象,我们直接看Window API的superDispatchTouchEvent()这个是个抽象方法,所以我们直接找到其子类来看看superDispatchTouchEvent()方法的具体逻辑实现,Window的唯一子类是PhoneWindow,我们就看看PhoneWindow的superDispatchKeyEvent()方法,里面直接调用DecorView类的superDispatchKeyEvent方法,或许很多人不了解DecorView这个类,DecorView是PhoneWindow的一个final的内部类并且继承FrameLayout的,也是Window界面的最顶层的View对象,该对象本质上是一个viewgroup对象。


android的视图组件分为有子组件的viewgroup 和 没有子组件的普通view。其中viewgroup继承view,首先分析一下view的Touch事件处理逻辑。

最开始接收到事件的viewgroup会调用view的dispatchTouchEvent(MotionEvent event)方法将事件传递给view,并且判断该事件有没有被子view消耗掉(当子view return true的时候,事件被消耗)掉,反之没有,这个如何处理会在viewgroup中分析)


以下是view中的dispatchTouchEvent的分析

public boolean dispatchTouchEvent(MotionEvent event) {       。。。。。            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED                    && li.mOnTouchListener.onTouch(this, event)) {                return true;            }            if (onTouchEvent(event)) {                return true;            }        }     。。。。。        return false;    }

通过代码可以清晰的看到view的dispatchTouchEvent方法很简单,首先判断mOnTouchListener.onTouch(this, event)方法执行的结果,如果返回true,那么说明该事件已经被外面复写的OnTouchListener接口消耗掉,否则调用该view的onTouchEvent()方法,该方法是对touch事件进行处理,如果该方法处理结果返回为true,那么说明事件被消耗掉。如果前面两种处理结果都不为true,那么说明该view没有消耗事件。


以下为view中ontouchevent()的分析

public boolean onTouchEvent(MotionEvent event) {     。。。。。       //如果设置了Touch代理,就交给代理来处理,mTouchDelegate默认是null      if (mTouchDelegate != null) {          if (mTouchDelegate.onTouchEvent(event)) {              return true;          }      } 。。。。。      //如果View是clickable或者longClickable的onTouchEvent就返回true, 否则返回false      if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {          switch (event.getAction()) {              case MotionEvent.ACTION_UP:                  boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;                  if ((mPrivateFlags & PRESSED) != 0 || prepressed) {                      boolean focusTaken = false;                      if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {                          focusTaken = requestFocus();                      }                       if (!mHasPerformedLongPress) {                          //移除longclick的回调接口                          removeLongPressCallback();                           if (!focusTaken) {                              if (mPerformClick == null) {                                  mPerformClick = new PerformClick();                              }                              //如果longclick返回为false,那么执行click事件                              if (!post(mPerformClick)) {                                  performClick();                              }                          }                      }                       if (mUnsetPressedState == null) {                          mUnsetPressedState = new UnsetPressedState();                      }                       if (prepressed) {                          mPrivateFlags |= PRESSED;                          refreshDrawableState();                          postDelayed(mUnsetPressedState,                                  ViewConfiguration.getPressedStateDuration());                      } else if (!post(mUnsetPressedState)) {                          mUnsetPressedState.run();                      }                      removeTapCallback();                  }                  break;               case MotionEvent.ACTION_DOWN:                  if (mPendingCheckForTap == null) {                      mPendingCheckForTap = new CheckForTap();                  }                  mPrivateFlags |= PREPRESSED;                  mHasPerformedLongPress = false;                  //启动longclick监听,当达到一定的时间,还没有执行ACTION_UP,那么会调用longclick接口                  postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());                  break;             //当接收到action_down事件后,如果父亲viewgroup截取了后续的move,up那么该view会收到cancle的消息             case MotionEvent.ACTION_CANCEL:                  mPrivateFlags &= ~PRESSED;                  refreshDrawableState();                  removeTapCallback();                  break;               case MotionEvent.ACTION_MOVE:                  final int x = (int) event.getX();                  final int y = (int) event.getY();                   //当手指在View上面滑动超过View的边界,                  int slop = mTouchSlop;                  if ((x < 0 - slop) || (x >= getWidth() + slop) ||                          (y < 0 - slop) || (y >= getHeight() + slop)) {                      // Outside button                      removeTapCallback();                      if ((mPrivateFlags & PRESSED) != 0) {                          removeLongPressCallback();                           mPrivateFlags &= ~PRESSED;                          refreshDrawableState();                      }                  }                  break;          }          return true;      }       return false;  }


下面分析比较复杂的viewgroup的dispatchTouchEvent方法,由于viewgroup继承于view,因此viewgroup中的dispatchTouchEvent方法是对view的dispatchTouchEvent方法的复写
   @Override   public boolean dispatchTouchEvent(MotionEvent ev) {       final int action = ev.getAction();       final float xf = ev.getX();       final float yf = ev.getY();       final float scrolledXFloat = xf + mScrollX;       final float scrolledYFloat = yf + mScrollY;       final Rect frame = mTempRect;        //这个值默认是false, 然后我们可以通过requestDisallowInterceptTouchEvent(boolean disallowIntercept)方法       //来改变disallowIntercept的值       boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;        //这里是ACTION_DOWN的处理逻辑       if (action == MotionEvent.ACTION_DOWN) {           //清除mMotionTarget, 每次ACTION_DOWN都很设置mMotionTarget为null           if (mMotionTarget != null) {               mMotionTarget = null;           }            //disallowIntercept默认是false, 就看ViewGroup的onInterceptTouchEvent()方法           if (disallowIntercept || !onInterceptTouchEvent(ev)) {               ev.setAction(MotionEvent.ACTION_DOWN);               final int scrolledXInt = (int) scrolledXFloat;               final int scrolledYInt = (int) scrolledYFloat;               final View[] children = mChildren;               final int count = mChildrenCount;               //遍历其子View               for (int i = count - 1; i >= 0; i--) {                   final View child = children[i];                                       //如果该子View是VISIBLE或者该子View正在执行动画, 表示该View才                   //可以接受到Touch事件                   if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE                           || child.getAnimation() != null) {                       //获取子View的位置范围                       child.getHitRect(frame);                                               //如Touch到屏幕上的点在该子View上面                       if (frame.contains(scrolledXInt, scrolledYInt)) {                           // offset the event to the view's coordinate system                           final float xc = scrolledXFloat - child.mLeft;                           final float yc = scrolledYFloat - child.mTop;                           ev.setLocation(xc, yc);                           child.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;                                                       //调用该子View的dispatchTouchEvent()方法                           if (child.dispatchTouchEvent(ev))  {                               // 如果child.dispatchTouchEvent(ev)返回true表示                               //该事件被消费了,设置mMotionTarget为该子View                               mMotionTarget = child;                               //直接返回true                               return true;                           }                           // The event didn't get handled, try the next view.                           // Don't reset the event's location, it's not                           // necessary here.                       }                   }               }           }       }        //判断是否为ACTION_UP或者ACTION_CANCEL       boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) ||               (action == MotionEvent.ACTION_CANCEL);        if (isUpOrCancel) {           //如果是ACTION_UP或者ACTION_CANCEL, 将disallowIntercept设置为默认的false           //假如我们调用了requestDisallowInterceptTouchEvent()方法来设置disallowIntercept为true           //当我们抬起手指或者取消Touch事件的时候要将disallowIntercept重置为false           //所以说上面的disallowIntercept默认在我们每次ACTION_DOWN的时候都是false           mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;       }        // The event wasn't an ACTION_DOWN, dispatch it to our target if       // we have one.       final View target = mMotionTarget;       //mMotionTarget为null意味着没有找到消费Touch事件的View, 所以我们需要调用ViewGroup父类的       //dispatchTouchEvent()方法,也就是View的dispatchTouchEvent()方法       if (target == null) {           // We don't have a target, this means we're handling the           // event as a regular view.           ev.setLocation(xf, yf);           if ((mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {               ev.setAction(MotionEvent.ACTION_CANCEL);               mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;           }           return super.dispatchTouchEvent(ev);       }        //这个if里面的代码ACTION_DOWN不会执行,只有ACTION_MOVE       //ACTION_UP才会走到这里, 假如在ACTION_MOVE或者ACTION_UP拦截的       //Touch事件, 将ACTION_CANCEL派发给target,然后直接返回true       //表示消费了此Touch事件       if (!disallowIntercept && onInterceptTouchEvent(ev)) {           final float xc = scrolledXFloat - (float) target.mLeft;           final float yc = scrolledYFloat - (float) target.mTop;           mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;           ev.setAction(MotionEvent.ACTION_CANCEL);           ev.setLocation(xc, yc);                       if (!target.dispatchTouchEvent(ev)) {           }           // clear the target           mMotionTarget = null;           // Don't dispatch this event to our own view, because we already           // saw it when intercepting; we just want to give the following           // event to the normal onTouchEvent().           return true;       }        if (isUpOrCancel) {           mMotionTarget = null;       }        // finally offset the event to the target's coordinate system and       // dispatch the event.       final float xc = scrolledXFloat - (float) target.mLeft;       final float yc = scrolledYFloat - (float) target.mTop;       ev.setLocation(xc, yc);        if ((target.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {           ev.setAction(MotionEvent.ACTION_CANCEL);           target.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;           mMotionTarget = null;       }        //如果没有拦截ACTION_MOVE, ACTION_DOWN的话,直接将Touch事件派发给target       return target.dispatchTouchEvent(ev);</span>

该方法的逻辑是这样的,首先如果接收到的是action_down事件,判断onInterceptTouchEvent方法有没有截取该事件,如果返回true则认为该viewgroup截取了该事件,那么直接调用该viewgroup的super.dispatchTouchEvent(ev)方法处理事件(就是调用父类view中的dispatchTouchEvent方法),不往自己的子view分派,如果返回false则认为该viewgroup没有截取该事件,那么从前往后遍历该viegroup的子view,调用他们的dispatchTouchEvent方法,如果有view截取了该事件,那么该view就是本次touch事件的target;如果没有view截取该事件,即子view所有的dispatchtouchevent方法返回都为false,那么直接调用该viewgroup的super.dispatchTouchEvent(ev)方法处理事件。依照此逻辑递归,直到找到某个target,对于后续的move,up事件,如果viewgroup没有截取他们,那么会调用target的dispatchTouchEvent方法,如果截取了他们,那么会向target发送一个cancle的事件,并且本次分派结果返回true,表示viewgroup消耗了本次事件。


总结:

1.viewgroup调用dispatchTouchEvent和onInterceptTouchEvent-------view查看touchlistener和ontouchevent,看看有没有处理掉该事件----------没有的话viewgroup调用自己的super.dispatchTouchEvent方法做处理--------还是没有消耗(return true),那么将事件返回给上一级,依次递归,最后如果都没有处理回传给最顶层的viewgroup,消耗掉本次事件

2.view的dispatchTouchEvent会先调用touchlistener的ontouch接口,只有当该接口返回为false的时候,才会调用ontouchevent方法

3.ontouchevent方法只有在view是clickable或者longClickable的时候才能进入switch case的逻辑,否则return false

4.对于click,touch和longclick的处理,当action_down事件发生的时候,会启动一个异步线程以确定过一段时间要执行longclick的接口回调,但是可以在action_up事件处理中remove掉该longclick回调接口,进一步在action_up事件处理的时候,如果longclick返回的是false,那么会执行一次click的接口回调,因而如果不要同时处理longclick和click,可以在longclick处返回true。总之click依赖于longclick,click和longclick依赖于touch事件

5.viewgroup+view的结构能够使得touch事件的从父视图向子视图的传递,并且viewgroup继承于view,也能够支持viewgroup自行处理touch事件以及处理子视图截取掉但是没有消耗掉的事件

1 0
原创粉丝点击