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

View的事件分發機制學習筆記

編輯:關於Android編程

好不容易周末有空,作為一個零基礎非計算機專業剛培訓出來7個月的小白,對付博大精深的Android源碼真的是心有余而力不足,但是東西還是要學滴,這不!找到Hongyang大神的博文結合任玉剛的《Android 開發藝術探索》的第3.4章的View的時間分發機制開始了艱難的自學中。。。,下面開始上代碼,

自定義一個控件

自定義一個個控件繼承 Button 通過重寫onTouchEvent方法和dispatchTouchEvent方法打印出日志,方便我們對View的事件分發機制進行分析:

package com.xuzhenhao.demos.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Button;

/**
 * For test MotionEvent
 * Created by Xuzhenhao on 2016/8/28.
 */
public class TestMotionEventView extends Button{


    private String TAG = TestMotionEventView.class.getSimpleName();

    private OnLogListener logListener;


    public TestMotionEventView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setOnLogListener(OnLogListener l){
        this.logListener = l;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event){

        int action = event.getAction();

        switch (action){

            case MotionEvent.ACTION_DOWN:
                Log.i(TAG,"onTouchEvent: ACTION_DOWN");
                logListener.writeLog("onTouchEvent: ACTION_DOWN\n");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.i(TAG,"onTouchEvent: ACTION_MOVE");
                logListener.writeLog("onTouchEvent: ACTION_MOVE\n");
                break;
            case MotionEvent.ACTION_UP:
                Log.i(TAG,"onTouchEvent: ACTION_UP");
                logListener.writeLog("onTouchEvent: ACTION_UP\n");
                break;
        }

        return super.onTouchEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {

        int action = event.getAction();

        switch(action){

            case MotionEvent.ACTION_DOWN:
                Log.i(TAG,"dispatchTouchEvent: ACTION_DOWN");
                logListener.writeLog("dispatchTouchEvent: ACTION_DOWN\n");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.i(TAG,"dispatchTouchEvent: ACTION_MOVE");
                logListener.writeLog("dispatchTouchEvent: ACTION_MOVE\n");
                break;
            case MotionEvent.ACTION_UP:
                Log.i(TAG,"dispatchTouchEvent: ACTION_UP");
                logListener.writeLog("dispatchTouchEvent: ACTION_UP\n");
                break;
        }


        return super.dispatchTouchEvent(event);
    }


    /**
     * 回調接口
     */
    public interface OnLogListener{

        /**
         * 將日志寫到Activity中的TextView
         * @param logs
         */
        public void writeLog(String logs);
    }
}
 

 

Activity的XML

 





    

    


下面就是Activity的代碼了

 

 

package com.xuzhenhao.demos;

import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.xuzhenhao.demos.view.TestMotionEventView;


/**
 * 沉浸式
 */
public class ImmerseActivity extends AppCompatActivity implements TestMotionEventView.OnLogListener{

    /* 日志TextView */
    private TextView logsTv;
    /* 測試按鈕 */
    private TestMotionEventView testBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_immerse);

        initView();
    }

    /**
     * 初始化控件
     */
    private void initView(){

        logsTv  = (TextView) findViewById(R.id.event_log);
        testBtn = (TestMotionEventView) findViewById(R.id.test_event_btn);

        testBtn.setOnLogListener(this);
        testBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                int action = motionEvent.getAction();
                switch(action){
                    case MotionEvent.ACTION_DOWN:
                        Log.i("ImmerseActivity", "onTouch: ACTION_DOWN");
                        setLogs("onTouch: ACTION_DOWN\n");
                        break;
                    case MotionEvent.ACTION_MOVE:
                        Log.i("ImmerseActivity", "onTouch: ACTION_MOVE");
                        setLogs("onTouch: ACTION_MOVE\n");
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.i("ImmerseActivity", "onTouch: ACTION_UP");
                        setLogs("onTouch: ACTION_UP\n");
                        break;

                }
                return false;
            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus){
        super.onWindowFocusChanged(hasFocus);
        /** 沉浸式只支持sdk 19及以上的 **/
        if (hasFocus && Build.VERSION.SDK_INT >= 19){
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

        }

    }

    @Override
    public void writeLog(String logs) {

        setLogs(logs);
    }


    /**
     * 給TestView設值
     * @param str
     */
    private void setLogs(String str){

        String logs = logsTv.getText().toString();
        logs = logs + str;
        logsTv.setText(logs);
    }
}

好了!做完這一切,下一步就是生成日志的時候了

\

根據日志的打印順序我們可以看到,我們觸摸按鈕後執行的方法分別是:

dispatchTouchEventsetOnTouchListener下的onTouchonTouchEvent

下面我們開始對這三個方法進行研究,這裡我偷來Hongyang大神的部分代碼,因為英語是硬傷。

dispatchTouchEvent

 

    /** 
      * Pass the touch screen motion event down to the target view, or this 
      * view if it is the target. 
      * 
      * @param event The motion event to be dispatched. 
      * @return True if the event was handled by the view, false otherwise. 
      */  
      public boolean dispatchTouchEvent(MotionEvent event) {  
          if (!onFilterTouchEventForSecurity(event)) {  
              return false;  
          }  
      
          if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&  
                  mOnTouchListener.onTouch(this, event)) {  
              return true;  
          }  
          return onTouchEvent(event);  
      }  

根據第13行:首先判斷mOnTouchListener不為null,並且view是enable的狀態,然後mOnTouchListener.onTouch(this, event)返回true,這三個條件如果都滿足,直接return true ; 也就是下面的onTouchEvent(event)不會被執行了;

 

 

那麼mOnTouchListener是和方神聖,我們來看看:

 

 /** 
   * Register a callback to be invoked when a touch event is sent to this view. 
   * @param l the touch listener to attach to this view 
   */  
   public void setOnTouchListener(OnTouchListener l) {  
       mOnTouchListener = l;  
   }  

 

其實就是我們在Activity中設置的setOnTouchListener。

也就是說:如果我們設置了setOnTouchListener,並且return true,那麼View自己的onTouchEvent就不會被執行了,當然了,本例我們return false,我們還得往下探索 ;

已經解決一個常見的問題:View的onTouchListener和onTouchEvent的調用關系,繼續往下。

onTouchEvent:

 

/** 
  * Implement this method to handle touch scren motion events. 
  * @param event The motion event. 
  * @return True if the event was handled, false otherwise. 
  */  
  public boolean onTouchEvent(MotionEvent event) {  
      final int viewFlags = mViewFlags;  
      
       if ((viewFlags & ENABLED_MASK) == DISABLED) {  
          // 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));  
          }  
      
      if (mTouchDelegate != null) {  
          if (mTouchDelegate.onTouchEvent(event)) {  
              return true;  
          }  
      }  
      
      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) {  
                      // 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 (!mHasPerformedLongPress) {  
                          // 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) {  
                          mPrivateFlags |= PRESSED;  
                          refreshDrawableState();  
                          postDelayed(mUnsetPressedState,  
                                  ViewConfiguration.getPressedStateDuration());  
                      } else if (!post(mUnsetPressedState)) {  
                          // If the post failed, unpress right now  
                          mUnsetPressedState.run();  
                      }  
                      removeTapCallback();  
                  }  
                  break;  
      
              case MotionEvent.ACTION_DOWN:  
                  if (mPendingCheckForTap == null) {  
                      mPendingCheckForTap = new CheckForTap();  
                  }  
                  mPrivateFlags |= PREPRESSED;  
                  mHasPerformedLongPress = false;  
                  postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());  
                  break;  
      
              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();  
      
                  // Be lenient about moving outside of buttons  
                  int slop = mTouchSlop;  
                  if ((x < 0 - slop) || (x >= getWidth() + slop) ||  
                          (y < 0 - slop) || (y >= getHeight() + slop)) {  
                      // Outside button 
                      removeTapCallback();  
                      if ((mPrivateFlags & PRESSED) != 0) {  
                          // Remove any future long press/tap checks  
                          removeLongPressCallback();  
      
                          // Need to switch from pressed to not pressed  
                          mPrivateFlags &= ~PRESSED;  
                          refreshDrawableState();  
                      }  
                  }  
                  break;  
          }  
          return true;  
      }  
      
      return false;  
  }  
 

 

9-15行,如果當前View是Disabled狀態且是可點擊則會消費掉事件(return true);可以忽略,不是我們的重點;

16-21行,如果設置了mTouchDelegate,則會將事件交給代理者處理,直接return true,如果大家希望自己的View增加它的touch范圍,可以嘗試使用TouchDelegate,這裡也不是重點,可以忽略;

接下來到我們的重點了:

22行的判斷:如果我們的View可以點擊或者可以長按,則,注意IF的范圍,最終一定return true ;

if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
//...
return true;
}

接下來就是 switch (event.getAction())了,判斷事件類型,DOWN,MOVE,UP等;

我們按照例子執行的順序,先看 case MotionEvent.ACTION_DOWN (70-78行):

MotionEvent.ACTION_DOWN

75行:給mPrivateFlags設置一個PREPRESSED的標識

76行:設置mHasPerformedLongPress=false;表示長按事件還未觸發;

77行:發送一個延遲為ViewConfiguration.getTapTimeout()的延遲消息,到達延時時間後會執行CheckForTap()裡面的run方法:

1、ViewConfiguration.getTapTimeout()為115毫秒;

2、CheckForTap

 

private final class CheckForTap implements Runnable {  
      public void run() {  
          mPrivateFlags &= ~PREPRESSED;  
          mPrivateFlags |= PRESSED;  
          refreshDrawableState();  
          if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {  
              postCheckForLongClick(ViewConfiguration.getTapTimeout());  
          }  
      }  
  }  
 

 

在run方法裡面取消mPrivateFlags的PREPRESSED,然後設置PRESSED標識,刷新背景,如果View支持長按事件,則再發一個延時消息,檢測長按;

private void postCheckForLongClick(int delayOffset) {  
       mHasPerformedLongPress = false;  
      
       if (mPendingCheckForLongPress == null) {  
           mPendingCheckForLongPress = new CheckForLongPress();  
       }  
       mPendingCheckForLongPress.rememberWindowAttachCount();  
       postDelayed(mPendingCheckForLongPress,  
               ViewConfiguration.getLongPressTimeout() - delayOffset);  
       }  

 

class CheckForLongPress implements Runnable {  
      
        private int mOriginalWindowAttachCount;  
      
        public void run() {  
            if (isPressed() && (mParent != null)  
                    && mOriginalWindowAttachCount == mWindowAttachCount) {  
                if (performLongClick()) {  
                    mHasPerformedLongPress = true;  
                }  
            }  
        }  
可以看到,當用戶按下,首先會設置標識為PREPRESSED

 

如果115後,沒有抬起,會將View的標識設置為PRESSED且去掉PREPRESSED標識,然後發出一個檢測長按的延遲任務,延時為:ViewConfiguration.getLongPressTimeout() - delayOffset(500ms -115ms),這個115ms剛好時檢測額PREPRESSED時間;也就是用戶從DOWN觸發開始算起,如果500ms內沒有抬起則認為觸發了長按事件:

1、如果此時設置了長按的回調,則執行長按時的回調,且如果長按的回調返回true;才把mHasPerformedLongPress置為ture;

2、否則,如果沒有設置長按回調或者長按回調返回的是false;則mHasPerformedLongPress依然是false;

好了DOWN就分析完成了;大家回個神,下面回到VIEW的onTouchEvent中的ACTION_MOVE:

MotionEvent.ACTION_MOVE

86到105行:

86-87行:拿到當前觸摸的x,y坐標;

91行判斷當然觸摸點有沒有移出我們的View,如果移出了:

1、執行removeTapCallback();

2、然後判斷是否包含PRESSED標識,如果包含,移除長按的檢查:removeLongPressCallback();

3、最後把mPrivateFlags中PRESSED標識去除,刷新背景;

private void removeTapCallback() {  
       if (mPendingCheckForTap != null) {  
           mPrivateFlags &= ~PREPRESSED;  
           removeCallbacks(mPendingCheckForTap);  
       }  
   }  
這個是移除,DOWN觸發時設置的PREPRESSED的檢測;即當前觸發時機在DOWN觸發不到115ms時,你就已經移出控件外了;

如果115ms後,你才移出控件外,則你的當前mPrivateFlags一定為PRESSED且發送了長按的檢測;

就會走上面的2和3;首先移除removeLongPressCallback()
private void removeLongPressCallback() {
if (mPendingCheckForLongPress != null) {
removeCallbacks(mPendingCheckForLongPress);
}
}

然後把mPrivateFlags中PRESSED標識去除,刷新背景;

好了,MOVE我們也分析完成了,總結一下:只要用戶移出了我們的控件:則將mPrivateFlags取出PRESSED標識,且移除所有在DOWN中設置的檢測,長按等;

下面再回個神,回到View的onTouchEvent的ACTION_UP:

 

MotionEvent.ACTION_UP

26到69行:

27行:判斷mPrivateFlags是否包含PREPRESSED

28行:如果包含PRESSED或者PREPRESSED則進入執行體,也就是無論是115ms內或者之後抬起都會進入執行體。

35行:如果mHasPerformedLongPress沒有被執行,進入IF

37行:removeLongPressCallback();移除長按的檢測

44-49行:如果mPerformClick如果mPerformClick為null,初始化一個實例,然後立即通過handler添加到消息隊列尾部,如果添加失敗則直接執行performClick();添加成功,在mPerformClick的run方法中就是執行performClick();

終於執行了我們的click事件了,下面看一下performClick()方法:

 

public boolean performClick() {  
       sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);  
      
       if (mOnClickListener != null) {  
           playSoundEffect(SoundEffectConstants.CLICK);  
           mOnClickListener.onClick(this);  
           return true;  
       }  
      
       return false;  
   }  
 

 

if (mOnClickListener != null) {
mOnClickListener.onClick(this);
return true;
}

久違了~我們的mOnClickListener ;

別激動,還沒結束,回到ACTION_UP,

58行:如果prepressed為true,進入IF體:

為mPrivateFlags設置表示為PRESSED,刷新背景,125毫秒後執行mUnsetPressedState

否則:mUnsetPressedState.run();立即執行;也就是不管咋樣,最後mUnsetPressedState.run()都會執行;

看看這個UnsetPressedState主要干什麼:

private final class UnsetPressedState implements Runnable {
public void run() {
setPressed(false);
}
}

public void setPressed(boolean pressed) {
if (pressed) {
mPrivateFlags |= PRESSED;
} else {
mPrivateFlags &= ~PRESSED;
}
refreshDrawableState();
dispatchSetPressed(pressed);
}

把我們的mPrivateFlags中的PRESSED取消,然後刷新背景,把setPress轉發下去。

ACTION_UP的最後一行:removeTapCallback(),如果mPendingCheckForTap不為null,移除;

總結

好了,代碼跨度還是相當大的,下面需要總結下:

1、整個View的事件轉發流程是:

View.dispatchEvent->View.setOnTouchListener->View.onTouchEvent

在dispatchTouchEvent中會進行OnTouchListener的判斷,如果OnTouchListener不為null且返回true,則表示事件被消費,onTouchEvent不會被執行;否則執行onTouchEvent。

2、onTouchEvent中的DOWN,MOVE,UP

DOWN時:

a、首先設置標志為PREPRESSED,設置mHasPerformedLongPress=false ;然後發出一個115ms後的mPendingCheckForTap;

b、如果115ms內沒有觸發UP,則將標志置為PRESSED,清除PREPRESSED標志,同時發出一個延時為500-115ms的,檢測長按任務消息;

c、如果500ms內(從DOWN觸發開始算),則會觸發LongClickListener:

此時如果LongClickListener不為null,則會執行回調,同時如果LongClickListener.onClick返回true,才把mHasPerformedLongPress設置為true;否則mHasPerformedLongPress依然為false;

 

MOVE時:

主要就是檢測用戶是否劃出控件,如果劃出了:

115ms內,直接移除mPendingCheckForTap;

115ms後,則將標志中的PRESSED去除,同時移除長按的檢查:removeLongPressCallback();

UP時:

a、如果115ms內,觸發UP,此時標志為PREPRESSED,則執行UnsetPressedState,setPressed(false);會把setPress轉發下去,可以在View中復寫dispatchSetPressed方法接收;

b、如果是115ms-500ms間,即長按還未發生,則首先移除長按檢測,執行onClick回調;

c、如果是500ms以後,那麼有兩種情況:

 

i.設置了onLongClickListener,且onLongClickListener.onClick返回true,則點擊事件OnClick事件無法觸發;

ii.沒有設置onLongClickListener或者onLongClickListener.onClick返回false,則點擊事件OnClick事件依然可以觸發;

d、最後執行mUnsetPressedState.run(),將setPressed傳遞下去,然後將PRESSED標識去除;

 

最後問個問題:

1、setOnLongClickListener和setOnClickListener是否只能執行一個。不是的,只要setOnLongClickListener中的onClick返回false,則兩個都會執行;返回true則長按會屏蔽setOnClickListener

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