Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android事件的分發機制詳解

Android事件的分發機制詳解

編輯:關於Android編程

在分析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監聽了。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved