Android事件的分发机制详解

Android事件的分发机制详解,第1张

概述在分析Android事件分发机制前,明确android的两大基础控件类型:View和ViewGroup。View即普通的控件,没有子布局的,如Button、TextView.ViewGroup继承自View,表示可以有子控件,如Linearlayout、Listview这些。今天

在分析AndroID事件分发机制前,明确androID的两大基础控件类型:VIEw和VIEwGroup。VIEw即普通的控件,没有子布局的,如button、TextVIEw. VIEwGroup继承自VIEw,表示可以有子控件,如linearlayout、ListvIEw这些。今天我们先来了解VIEw的事件分发机制。
先看下代码,非常简单,只有一个button,分别给它注册了OnClick和Ontouch的点击事件。

btn.setonClickListener(new VIEw.OnClickListener() {      @OverrIDe      public voID onClick(VIEw v) {        Log.i("Tag","This is button onClick event");      }    });    btn.setontouchListener(new VIEw.OntouchListener() {      @OverrIDe      public boolean ontouch(VIEw v,MotionEvent event) {        Log.i("Tag","This is button ontouch action" + event.getAction());        return false;      }    });

运行一下项目,结果如下:
 I/Tag: This is button ontouch action0
 I/Tag: This is button ontouch action2
 I/Tag: This is button ontouch action2
 I/Tag: This is button ontouch action1
 I/Tag: This is button onClick event 
可以看到,ontouch是有先于onClick执行的,因此事件的传递顺序是先ontouch,在到OnClick。具体为什么这样,下面会通过源码来说明。这时,我们可能注意到了,ontouch的方法是有返回值,这里是返回false,我们将它改为true再运行一次,结果如下:
 I/Tag: This is button ontouch action0
 I/Tag: This is button ontouch action2
 I/Tag: This is button ontouch action2
 I/Tag: This is button ontouch action2
 I/Tag: This is button ontouch action1

对比两次结果,我们发现onClick方法不再执行,为什么会这样,下面我将通过源码给大家一步步理清这个思路。
查看源码时,首先要知道所有VIEw类型控件事件入口都是dispatchtouchEvent(),所以我们直接进入到VIEw这个类里面的dispatchtouchEvent()方法看一下。 

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);    }    boolean result = false;    if (m@R_419_5983@EventConsistencyVerifIEr != null) {      m@R_419_5983@EventConsistencyVerifIEr.ontouchEvent(event,0);    }    final int actionMasked = event.getActionMasked();    if (actionMasked == MotionEvent.ACTION_DOWN) {      // Defensive cleanup for new gesture      stopnestedScroll();    }    if (onFiltertouchEventForSecurity(event)) {      //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;      }    }    if (!result && m@R_419_5983@EventConsistencyVerifIEr != null) {      m@R_419_5983@EventConsistencyVerifIEr.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();    }    return result;  }

从源码第25行处可以看到,mOntouchListener.ontouch()的方法首先被执行,如果li != null && li.mOntouchListener != null&& (mVIEwFlags & ENABLED_MASK) == ENABLED&& li.mOntouchListener.ontouch(this,event)都为真的话,result赋值为true,否则就执行ontouchEvent(event)方法。

从上面可以看到要符合条件有四个,
 1、ListenerInfo li,它是vIEw中的一个静态类,里面定义vIEw的事件的监听等等,所以有涉及到vIEw的事件,ListenerInfo都会被实例化,因此li不为null
 2、mOntouchiListener是在setontouchListener方法里面赋值的,只要touch事件被注册,mOntouchiListener一定不会null
 3、 (mVIEwFlags & ENABLED_MASK) == ENABLED,是判断当前点击的控件是否是enable的,button默认为enable,这个条件也恒定为true,
 4、重点来了,li.mOntouchListener.ontouch(this,event)就是回调控件ontouch方法,当这个条件也为true时,result=true,ontouchEvent(event)将不会被执行。如果ontouch返回false,就会再执行ontouchEvent(event)方法。
我们接着再进入到ontouchEvent方法查看源码。

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);    }    if (mtouchDelegate != null) {      if (mtouchDelegate.ontouchEvent(event)) {        return true;      }    }    if (((vIEwFlags & CliCKABLE) == CliCKABLE ||        (vIEwFlags & LONG_CliCKABLE) == LONG_CliCKABLE) ||        (vIEwFlags & CONTEXT_CliCKABLE) == CONTEXT_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);            }            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 (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();          }          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,y);            checkForLongClick(0);          }          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;    }    return false;  }

从源码的21行我们可以看出,该控件可点击就会进入到switch判断中,当我们触发了手指离开的实际,则会进入到MotionEvent.ACTION_UP这个case当中。我们接着往下看,在源码的50行,调用到了mPerformClick()方法,我们继续进入到这个方法的源码看看。 

public boolean performClick() {    final boolean result;    final ListenerInfo li = mListenerInfo;    if (li != null && li.mOnClickListener != null) {      playSoundEffect(SoundEffectConstants.CliCK);      li.mOnClickListener.onClick(this);      result = true;    } else {      result = false;    }    sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CliCKED);    return result;  }

现在我们可以看到,只要ListenerInfo和mOnClickListener不为null就会调用onClick这个方法,之前说过,只要有监听事件,ListenerInfo就不为null,带mOnClickListener又是在哪里赋值呢?我们再继续看下它的源码。

public voID setonClickListener(@Nullable OnClickListener l) {    if (!isClickable()) {      setClickable(true);    }    getListenerInfo().mOnClickListener = l;  }

看到这里一切就清楚了,当我们调用setonClickListener方法来给按钮注册一个点击事件时,就会给mOnClickListener赋值。整个分发事件的顺序是ontouch()-->ontouchEvent(event)-->performClick()-->OnClick()。
 现在我们可以解决之前的问题。
1、ontouch方法是优先于OnClick,所以是执行了ontouch,再执行onClick。 
2、无论是dispatchtouchEvent还是ontouchEvent,如果返回true表示这个事件已经被消费、处理了,不再往下传了。在dispathtouchEvent的源码里可以看到,如果ontouchEvent返回了true,那么它也返回true。如果dispatchtouchEvent在执行ontouch监听的时候,ontouch返回了true,那么它也返回true,这个事件提前被ontouch消费掉了。就不再执行ontouchEvent了,更别说onClick监听了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android事件的分发机制详解全部内容,希望文章能够帮你解决Android事件的分发机制详解所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1149158.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存