首页 > 系统 > Android > 正文

Android事件的分发机制详解

2019-12-12 06:11:26
字体:
来源:转载
供稿:网友

在分析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 (mInputEventConsistencyVerifier != null) {      mInputEventConsistencyVerifier.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 && 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();    }    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, x, 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监听了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表