关闭

View的事件分发机制学习笔记

标签: View事件分发机制
267人阅读 评论(0) 收藏 举报
分类:

好不容易周末有空,作为一个零基础非计算机专业刚培训出来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

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.xuzhenhao.demos.ImmerseActivity">


    <TextView
        android:id="@+id/event_log"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:layout_marginTop="20dp"
        android:scrollbarStyle="outsideInset"
        android:hint="点击按钮,获取事件日志" />

    <com.xuzhenhao.demos.view.TestMotionEventView
        android:id="@+id/test_event_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/event_log"
        android:text="事件分发机制"/>

</RelativeLayout>
下面就是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);
    }
}

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

                                            

根据日志的打印顺序我们可以看到,我们触摸按钮后执行的方法分别是:

  1. dispatchTouchEvent
  2. setOnTouchListener下的onTouch
  3. onTouchEvent

下面我们开始对这三个方法进行研究,这里我偷来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





0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4698次
    • 积分:268
    • 等级:
    • 排名:千里之外
    • 原创:20篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条