Android的触摸分发机制和如何实现拦截

  • Android的触摸分发机制和如何实现拦截

    • 前言
    • 触摸事件的分发
    • 情景分析
    • 总结

前言

在自定义ViewGroup中,有时候需要实现触摸事件拦截,比如ListView下拉刷新就是典型的触摸事件拦截的例子。触摸事件拦截就是在触摸事件被parent view拦截,而不会分发给其child,即使触摸发生在该child身上。被拦截的事件会转到parent view的onTouchEvent方法中进行处理。但是这个交互过程还是挺复杂的,有多种情况,今天我们就来分析一下吧。这篇分析文章已经放了一段时间了,如果有任何问题请高人指出。

触摸事件的分发

简单来说触摸事件的分发会经过这么几个顺序,dispatchTouchEvent –> onInterceptTouchEvent –> onTouchEvent,

假设一个Activity展示的界面有A->B->C->D四层,当事件发生之后,首先经过A的onInterceptTouchEvent(), 如果A的onInterceptTouchEvent()返回false,则会传递到B的onInterceptTouchEvent(),如果返回false则一次向下(内层)传递。如果某一层的onInterceptTouchEvent()返回true,然后就会调用该层的disatchTouchEvent()分发事件,事件不再向下传递。如果各层都没有拦截事件则从最内层开始调用dispatchTouchEvent(),如果某一各层的dispatchTouchEvent()返回true,则表明该层消费了该事件,则上面层的dispatchTouEvent()不会被调用。举一个例子:

 上图中B层的onInterceptTouchEvent()返回true,则事件被拦截,开始调用B层的dispatchTouchEvent()向上返回一次响应触摸事件。


事件拦截就在onInterceptTouchEvent方法中进行,在该方法中返回true即代表拦截触摸事件。触摸事件的分发是一个典型的隧道事件,即从上到下的过程。从视图树角度上来说,就是触摸事件会从父视图挨个传递到子视图。比如一个LinearLayout中又一个TextView,当触摸这个TextView时触摸事件会先打到LinearLayout,然后再到达TextView。如果LinearLayout将触摸事件拦截了,那么TextView就会收到一个CANCEL事件,其他触摸就收不到了。但是触摸事件的处理过程是一个冒泡事件,还是以上面的TextView为例,正常情况下,事件从上到下分发到TextView上,TextView则会对该事件进行处理,如果TextView处理了该事件,即TextView的dispatchTouchEvent返回了true, 那么该事件就被消费了。但是如果TextView的dispatchTouchEvent返回的是false, 则代表这个事件没有被处理,此时该事件就会从下到上(即从child 到 view group的过程)找parent view进行处理。如果parent view也没有处理,那么最终会交给Activity (如果是Activity窗口) 的onTouchEvent来处理。下面就是ViewGroup的事件分发过程,更详细的资料请参考Android Touch事件分发过程。
触摸事件的拦截

ViewGroup对于事件的拦截是一个复杂的流程,如果你想对触摸事件进行拦截,那么你需要覆写onInterceptTouchEvent方法,并且返回true。然后后续的事件就会被转移到该ViewGroup的onTouchEvent方法进行处理,而在后续的事件处理过程中onInterceptTouchEvent中也不会收到后续事件,因此你也需要覆写onTouchEvent方法。我们首先看看onInterceptTouchEvent方法的官方说明 :


Implement this method to intercept all touch screen motion events. This allows you to watch events as they are dispatched to your children, and take ownership of the current gesture at any point.Using this function takes some care, as it has a fairly complicated interaction with View.onTouchEvent(MotionEvent), and using it requires implementing that method as well as this one in the correct way. Events will be received in the following order:You will receive the down event here.
The down event will be handled either by a child of this view group, or given to your own onTouchEvent() method to handle; this means you should implement onTouchEvent() to return true, so you will continue to see the rest of the gesture (instead of looking for a parent view to handle it). Also, by returning true from onTouchEvent(), you will not receive any following events in onInterceptTouchEvent() and all touch processing must happen in onTouchEvent() like normal.For as long as you return false from this function, each following event (up to and including the final up) will be delivered first here and then to the target's onTouchEvent().If you return true from here, you will not receive any following events: the target view will receive the same event but with the action ACTION_CANCEL, and all further events will be delivered to your onTouchEvent() method and no longer appear here.
  • 翻译如下 :
    实现这个方法来拦截所有触摸事件。这会使得您可以监控到所有分发到你的子视图的事件,然后您可以随时控制当前的手势。
    使用这个方法您需要花些精力,因为它与View.onTouchEvent(MotionEvent)的交互非常复杂,并且要想使用这个功能还需要把当前ViewGroup的onTouchEvent方法和子控件的onTouchEvent方法正确地结合在一起使用。事件获取顺序如下:

  • 你将从这里开始接收ACTION_DOWN触摸事件。
    ACTION_DOWN触摸事件可以由该ViewGroup自己处理,也可以由它的子控件的onTouchEvent进行处理;这就意味着你需要实现onTouchEvent(MotionEvent)方法并且返回true,这样你才可以接收到后续的事件(以免会继续寻找父控件进行处理)。如果你在onTouchEvent(MotionEvent)返回了true,那么在onInterceptTouchEvent()方法中您将不会再收到后续的事件,所有这些后续的事件(例如您在ACTION_DOWN中返回了true,那么ACTION_MOVE, ACTION_UP这些成为后续事件)将会被本类的onTouchEvent(MotionEvent)方法中被处理。


只要您在onInterceptTouchEvent方法中返回false,每个后续的事件(从当前事件到最后ACTION_UP事件)将会先分发到onInterceptTouchEvent中,然后再交给目标子控件的onTouchEvent处理 (前提是子控件的onTouchEvent返回是true )。

如果在onInterceptTouchEvent返回true,onInterceptTouchEvent方法中将不会收到后续的任何事件,目标子控件中除了ACTION_CANCEL外也不会接收所有这些后续事件,所有的后续事件将会被交付到你自己的onTouchEvent()方法中。


触摸事件拦截示例

TouchLayout类 ( ViewGroup )

import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.FrameLayout;
import android.widget.Scroller;public class TouchLayout extends FrameLayout {private String TAG = TouchLayout.class.getSimpleName();public TouchLayout(Context context) {super(context);}public TouchLayout(Context context, AttributeSet attrs) {this(context, attrs, 0);}public TouchLayout(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);
//        setClickable(true);}@Overridepublic boolean dispatchTouchEvent(MotionEvent ev) {boolean result = super.dispatchTouchEvent(ev) ;return result;}@Overridepublic boolean onInterceptTouchEvent(MotionEvent ev) {// final int action = MotionEventCompat.getActionMasked(ev);// Always handle the case of the touch gesture being complete.if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {// Do not intercept touch event, let the child handle itreturn false;}TouchUtils.showEventInfo(TAG + "#   onInterceptTouchEvent", action);return false;}@Overridepublic boolean onTouchEvent(MotionEvent ev) {TouchUtils.showEventInfo(TAG + "# *** onTouchEvent", ev.getAction());Log.d(TAG, "### is Clickable = " + isClickable());return super.onTouchEvent(ev);
//        return true;}}

TouchTv ( View 类型)

public class TouchTv extends TextView {private String TAG = TouchTv.class.getSimpleName();public TouchTv(Context context) {this(context, null);}public TouchTv(Context context, AttributeSet attrs) {this(context, attrs, 0);}public TouchTv(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);
//        setClickable(true);}@Overridepublic boolean dispatchTouchEvent(MotionEvent ev) {TouchUtils.showEventInfo(TAG + "#dispatchTouchEvent", ev.getAction());boolean result = super.dispatchTouchEvent(ev);Log.d(TAG, "### dispatchTouchEvent result = " + result);return result;}@Overridepublic boolean onTouchEvent(MotionEvent ev) {TouchUtils.showEventInfo(TAG + "#onTouchEvent", ev.getAction());boolean result = super.onTouchEvent(ev);Log.d(TAG, "### onTouchEvent result = " + result);return result;}
}

Activity :

public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.touch_event_intercept);View myView = findViewById(R.id.my_button);ValueAnimator colorAnim = ObjectAnimator.ofInt(myView,"backgroundColor", /* Red */0xFFFF8080, /* Blue */0xFF8080FF);colorAnim.setDuration(3000);colorAnim.setEvaluator(new ArgbEvaluator());colorAnim.setRepeatCount(ValueAnimator.INFINITE);colorAnim.setRepeatMode(ValueAnimator.REVERSE);colorAnim.start();ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(myView, "scaleX",0.5f);objectAnimator.setDuration(3000);objectAnimator.setRepeatMode(ObjectAnimator.REVERSE);objectAnimator.start();Log.d("", "### Activiti中getWindow()获取的类型是 : " + this.getWindow());// state listStateListDrawable stateListDrawable = new StateListDrawable();stateListDrawable.addState(new int[] {android.R.attr.state_enabled}, getResources().getDrawable(R.drawable.ic_launcher));stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, getResources().getDrawable(R.drawable.ic_launcher));}@Overridepublic boolean dispatchTouchEvent(MotionEvent ev) {// Log.d("", "### activity dispatchTouchEvent");return super.dispatchTouchEvent(ev);}@Overridepublic boolean onTouchEvent(MotionEvent event) {TouchUtils.showEventInfo("activity onTouchEvent", event.getAction());return super.onTouchEvent(event);}}

touch_event_intercept.xml :

<myview.touchlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" tools:context="com.example.touch_event.MainActivity" tools:ignore="MergeRootFrame"><myview.touchtv android:id="@+id/my_button" android:layout_width="match_parent" android:layout_height="160dp" android:layout_gravity="center" android:layout_margin="20dp" android:background="#00aa00" android:gravity="center" android:text="@string/hello_world" android:textsize="30sp"></myview.touchtv></myview.touchlayout>

情景分析

以下的情景的触摸事件都是在TouchTv的范围内。

  • 情景1

    • 条件 : 在TouchLayout的onInterceptTouchEvent中返回true进行事件拦截, 在TouchLayout的onTouchEvent中返回 true消费事件;
      说明 : 触摸事件被拦截,后续的事件不会进入到onInterceptTouchEvent ( If you return true from here, you will not receive any following events ),而直接进入TouchLayout的onTouchEvent方法进行处理。onTouchEvent返回true,表明事件被消费了,不会再冒泡给上面的Parent进行处理;
      输出 :
// 事件拦截
10-01 20:22:52.892: D/TouchLayout#   onInterceptTouchEvent(407): ### action -->  ACTION_DOWN
// 处理
10-01 20:22:52.892: D/TouchLayout# *** onTouchEvent(407): ### action -->  ACTION_DOWN
// DOWN的后续事件不经过onInterceptTouchEvent,直接交给TouchLayout的onTouchEvent处理
10-01 20:22:52.917: D/TouchLayout# *** onTouchEvent(407): ### action -->  ACTION_MOVE
10-01 20:22:52.937: D/TouchLayout# *** onTouchEvent(407): ### action -->  ACTION_MOVE
10-01 20:22:52.957: D/TouchLayout# *** onTouchEvent(407): ### action -->  ACTION_MOVE
10-01 20:22:52.977: D/TouchLayout# *** onTouchEvent(407): ### action -->  ACTION_MOVE
10-01 20:22:52.977: D/TouchLayout# *** onTouchEvent(407): ### action -->  ACTION_MOVE
10-01 20:22:52.997: D/TouchLayout# *** onTouchEvent(407): ### action -->  ACTION_MOVE
10-01 20:22:53.017: D/TouchLayout# *** onTouchEvent(407): ### action -->  ACTION_MOVE
10-01 20:22:53.017: D/TouchLayout# *** onTouchEvent(407): ### action -->  ACTION_UP
  • 情景2

    • 条件 : 在TouchLayout的onInterceptTouchEvent中在ACTION_MOVE事件时返回true进行事件拦截, TouchTv的onTouchEvent中返回false,在TouchLayout的onTouchEvent中返回 true消费事件;
      说明 : 事件被拦截之前,会被分发给TouchTv的onTouchEvent进行处理;触摸事件被拦截之后,后续的事件不会进入到onInterceptTouchEvent,也不会交给TouchTv的onTouchEvent进行处理,而是直接进入TouchLayout的onTouchEvent方法进行处理。onTouchEvent返回true,表明事件被消费了,不会再冒泡给上面的Parent进行处理;
      输出 :
// DOWN中没有对事件进行拦截,因此可以被TouchTv进行处理
10-01 20:32:05.017: D/TouchLayout#   onInterceptTouchEvent(573): ### action -->  ACTION_DOWN
// TouchTv事件分发
10-01 20:32:05.017: D/TouchTv#dispatchTouchEvent(573): ### action -->  ACTION_DOWN
// TouchTv对事件进行处理,TouchTv的onTouchEvent返回false,导致事件交给TouchLayout的onTouchEvent处理
10-01 20:32:05.017: D/TouchTv#onTouchEvent(573): ### action -->  ACTION_DOWN
// TouchLayout的onTouchEvent处理DOWN事件
10-01 20:32:05.017: D/TouchLayout# *** onTouchEvent(573): ### action -->  ACTION_DOWN
// TouchLayout的onTouchEvent处理后续事件
10-01 20:32:05.062: D/TouchLayout# *** onTouchEvent(573): ### action -->  ACTION_MOVE
10-01 20:32:05.082: D/TouchLayout# *** onTouchEvent(573): ### action -->  ACTION_MOVE
10-01 20:32:05.267: D/TouchLayout# *** onTouchEvent(573): ### action -->  ACTION_MOVE
10-01 20:32:05.287: D/TouchLayout# *** onTouchEvent(573): ### action -->  ACTION_MOVE
10-01 20:32:05.307: D/TouchLayout# *** onTouchEvent(573): ### action -->  ACTION_MOVE
10-01 20:32:05.307: D/TouchLayout# *** onTouchEvent(573): ### action -->  ACTION_MOVE
10-01 20:32:05.312: D/TouchLayout# *** onTouchEvent(573): ### action -->  ACTION_UP
  • 情景3

    • 条件 : 在TouchLayout的onInterceptTouchEvent中返回true进行事件拦截, 但在TouchLayout的onTouchEvent中返回FALSE, 导致事件没有被消费;
      说明 : 触摸事件被拦截,后续的事件不会进入到onInterceptTouchEvent,而直接进入TouchLayout的onTouchEvent方法进行处理。onTouchEvent返回false,表明事件没有被消费,需要交给parent处理,如果最终该事件没有被处理,那么事件交给Activity的onTouchEvent处理。
      输出 :
// 事件拦截onInterceptTouchEvent
10-01 20:16:03.617: D/TouchLayout#   onInterceptTouchEvent(32675): ### action -->  ACTION_DOWN
// 事件处理onTouchEvent
10-01 20:16:03.617: D/TouchLayout# *** onTouchEvent(32675): ### action -->  ACTION_DOWN
// TouchLayout的dispatchTouchEvent最终返回了false,
10-01 20:16:03.617: D/TouchLayout(32675): ### dispatchTouchEvent, return false
// 事件没有被处理,最终交给了Activity的onTouchEvent处理
10-01 20:16:03.617: D/activity onTouchEvent(32675): ### action -->  ACTION_DOWN
10-01 20:16:03.697: D/activity onTouchEvent(32675): ### action -->  ACTION_MOVE
10-01 20:16:03.712: D/activity onTouchEvent(32675): ### action -->  ACTION_MOVE
10-01 20:16:03.732: D/activity onTouchEvent(32675): ### action -->  ACTION_MOVE
10-01 20:16:03.882: D/activity onTouchEvent(32675): ### action -->  ACTION_MOVE
10-01 20:16:03.897: D/activity onTouchEvent(32675): ### action -->  ACTION_MOVE
10-01 20:16:03.917: D/activity onTouchEvent(32675): ### action -->  ACTION_UP
  • 情景4

    • 条件 : 在TouchLayout的onInterceptTouchEvent中返回FALSE,不对触摸进行事件拦截, TouchLayout的onTouchEvent中返回true,但在TouchTv的onTouchEvent中返回FALSE, 导致事件没有被消费;
      说明 : 触摸事件不进行拦截,因此事件最终进入到TouchTv的onTouchEvent,但其返回false,表明事件没有被消费,需要交给parent处理,如果最终该事件没有被处理,那么事件交给Activity的onTouchEvent处理。
      输出 :
      “`
      // TouchLayout不对事件进行拦截
      10-01 20:43:04.682: D/TouchLayout# onInterceptTouchEvent(814): ### action –> ACTION_DOWN
      // 事件被TouchTv分发
      10-01 20:43:04.682: D/TouchTv#dispatchTouchEvent(814): ### action –> ACTION_DOWN
      // 事件被TouchTv处理
      10-01 20:43:04.682: D/TouchTv#onTouchEvent(814): ### action –> ACTION_DOWN
      // 事件被TouchTv的处理结果为false,因此该事件需要找parent来处理
      10-01 20:43:04.682: D/TouchTv(814): ### dispatchTouchEvent result = false
      // 事件被交给TouchTv的parent的onTouchEvent处理,即TouchLayout的onTouchEvent,该方法返回true
      // 因此后续事件继续交给TouchLayout处理
      10-01 20:43:04.682: D/TouchLayout# * onTouchEvent(814): ### action –> ACTION_DOWN
      10-01 20:43:04.727: D/TouchLayout# * onTouchEvent(814): ### action –> ACTION_MOVE
      10-01 20:43:04.747: D/TouchLayout# * onTouchEvent(814): ### action –> ACTION_MOVE
      10-01 20:43:04.872: D/TouchLayout# * onTouchEvent(814): ### action –> ACTION_MOVE
      10-01 20:43:04.892: D/TouchLayout# * onTouchEvent(814): ### action –> ACTION_MOVE
      10-01 20:43:04.892: D/TouchLayout# * onTouchEvent(814): ### action –> ACTION_UP

* 情景5* 条件 : 在TouchLayout的onInterceptTouchEvent中返回FALSE,不对触摸进行事件拦截, 但在TouchTv的onTouchEvent中返回true, 导致事件被消费;
说明 : 触摸事件不进行拦截,因此事件最终进入到TouchTv的onTouchEvent,但其返回true,表明事件没有被消费,那么后续事件将会先到TouchLayout的onInterceptTouchEvent,然后再分发给TouchTv。原文描述为 : For as long as you return false from this function, each following event (up to and including the final up) will be delivered first here and then to the target's onTouchEvent().
输出 : ```
// TouchLayout不拦截事件,因此事件分发给TouchTv进行处理,而TouchTv的处理结果为true,因此后续的事件将会先从
// TouchLayout的onInterceptTouchEvent再到TouchTv的onTouchEvent
10-01 20:48:49.612: D/TouchLayout#   onInterceptTouchEvent(1030): ### action -->  ACTION_DOWN
// TouchTv处理事件
10-01 20:48:49.612: D/TouchTv#dispatchTouchEvent(1030): ### action -->  ACTION_DOWN
10-01 20:48:49.612: D/TouchTv#onTouchEvent(1030): ### action -->  ACTION_DOWN
10-01 20:48:49.612: D/TouchTv(1030): ### dispatchTouchEvent result = true
// 后续事件从TouchLayout的onInterceptTouchEvent再到TouchTv的onTouchEvent
10-01 20:48:49.697: D/TouchLayout#   onInterceptTouchEvent(1030): ### action -->  ACTION_MOVE
10-01 20:48:49.697: D/TouchTv#dispatchTouchEvent(1030): ### action -->  ACTION_MOVE
10-01 20:48:49.697: D/TouchTv#onTouchEvent(1030): ### action -->  ACTION_MOVE
10-01 20:48:49.697: D/TouchTv(1030): ### dispatchTouchEvent result = true
10-01 20:48:49.717: D/TouchLayout#   onInterceptTouchEvent(1030): ### action -->  ACTION_MOVE
10-01 20:48:49.717: D/TouchTv#dispatchTouchEvent(1030): ### action -->  ACTION_MOVE
10-01 20:48:49.717: D/TouchTv#onTouchEvent(1030): ### action -->  ACTION_MOVE
10-01 20:48:49.717: D/TouchTv(1030): ### dispatchTouchEvent result = true
// UP事件直接在TouchTv中进行分发
10-01 20:48:49.782: D/TouchTv#dispatchTouchEvent(1030): ### action -->  ACTION_UP
10-01 20:48:49.782: D/TouchTv#onTouchEvent(1030): ### action -->  ACTION_UP
10-01 20:48:49.782: D/TouchTv(1030): ### dispatchTouchEvent result = true```
* 情景6*  条件 : 在TouchLayout的onInterceptTouchEvent中的DOWN事件中返回FALSE,但在MOVE事件中返回true, 且TouchTv的onTouchEvent返回true。
说明 : 触摸事件对DOWN事件不进行拦截,因此TouchTv可以正常的处理。但是在MOVE时对事件进行了拦截,那么TouchTv就无法接收到MOVE以及后面的事件了,它会收到一个CANCEL事件,后续的事件将会被TouchLayout的onTouchEvent进行处理。( If you return true from here, you will not receive any following events: the target view will receive the same event but with the action ACTION_CANCEL, and all further events will be delivered to your onTouchEvent() method and no longer appear here. )
输出 :```
// TouchLayout不对DOWN进行拦截
10-01 20:56:37.642: D/TouchLayout#   onInterceptTouchEvent(1205): ### action -->  ACTION_DOWN
// TouchTv分发与处理DOWN事件
10-01 20:56:37.642: D/TouchTv#dispatchTouchEvent(1205): ### action -->  ACTION_DOWN
10-01 20:56:37.642: D/TouchTv#onTouchEvent(1205): ### action -->  ACTION_DOWN
10-01 20:56:37.642: D/TouchTv(1205): ### dispatchTouchEvent result = true
// TouchLayout对MOVE事件进行拦截
10-01 20:56:37.712: D/TouchLayout#   onInterceptTouchEvent(1205): ### action -->  ACTION_MOVE
// TouchTv收到一个CANCEL事件,然后不会不到MOVE以及后续的事件
10-01 20:56:37.712: D/TouchTv#dispatchTouchEvent(1205): ### action -->  ACTION_CANCEL
10-01 20:56:37.712: D/TouchTv#onTouchEvent(1205): ### action -->  ACTION_CANCEL
10-01 20:56:37.712: D/TouchTv(1205): ### dispatchTouchEvent result = true
// MOVE以及后续事件被TouchLayout处理
10-01 20:56:37.727: D/TouchLayout# *** onTouchEvent(1205): ### action -->  ACTION_MOVE
10-01 20:56:37.747: D/TouchLayout# *** onTouchEvent(1205): ### action -->  ACTION_MOVE
10-01 20:56:37.762: D/TouchLayout# *** onTouchEvent(1205): ### action -->  ACTION_MOVE
10-01 20:56:37.777: D/TouchLayout# *** onTouchEvent(1205): ### action -->  ACTION_MOVE
10-01 20:56:37.797: D/TouchLayout# *** onTouchEvent(1205): ### action -->  ACTION_MOVE
10-01 20:56:37.997: D/TouchLayout# *** onTouchEvent(1205): ### action -->  ACTION_MOVE
10-01 20:56:38.012: D/TouchLayout# *** onTouchEvent(1205): ### action -->  ACTION_MOVE
10-01 20:56:38.017: D/TouchLayout# *** onTouchEvent(1205): ### action -->  ACTION_UP

总结

以上的几种情况就是我们经常遇到的了,总结起来有几个重要的点 :
1、如果Parent ViewGroup的onInterceptTouchEvent返回false, 并且触摸的目标view对于触摸事件的处理结果返回的是true,那么后续事件会先经过parent 的onInterceptTouchEvent, 然后再交给目标view进行处理;
2、如果Parent ViewGroup的onInterceptTouchEvent返回true,即对事件进行拦截,那么事件将不会再经过onInterceptTouchEvent,而是直接进入到onTouchEvent进行处理;如果onTouchEvent返回true,则表示该事件被处理了;如果返回FALSE,则代表事件没有被处理,那么事件会被上交给它的parent来处理,如果没有parent来处理,那么最终会交给Activity来处理;
3、如果用户在触摸的某个事件才拦截,那么目标view会收到一个CANCEL事件,然后后续的事件不会再交给目标view,而被转交给Parent的onTouchEvent方法进行处理。比如情景6当中,在TouchLayout的DOWN时不对事件进行拦截,这时事件会被TouchTv正常处理。但是在MOVE时事件被拦截了,此时TouchTv收到了一个CANCEL事件,MOVE以及后续的事件就交给了TouchLayout进行处理。这个情景就是我们做下拉刷新时要用的场景了。 我们结合ViewGroup的事件分发过程来验证吧。代码如下 :

/** * {@inheritDoc} */
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {  if (!onFilterTouchEventForSecurity(ev)) {  return false;  }  final int action = ev.getAction();  final float xf = ev.getX();  final float yf = ev.getY();  final float scrolledXFloat = xf + mScrollX;  final float scrolledYFloat = yf + mScrollY;  final Rect frame = mTempRect;  // 是否禁用拦截,如果为true表示不能拦截事件;反之,则为可以拦截事件  boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;  // ACTION_DOWN事件,即按下事件  if (action == MotionEvent.ACTION_DOWN) {  if (mMotionTarget != null) {  mMotionTarget = null;  }  // If we're disallowing intercept or if we're allowing and we didn't  // intercept。如果不允许事件拦截或者不拦截该事件,那么执行下面的操作  if (disallowIntercept || !onInterceptTouchEvent(ev))         // 1、是否禁用拦截、是否拦截事件的判断  // reset this event's action (just to protect ourselves)  ev.setAction(MotionEvent.ACTION_DOWN);  // We know we want to dispatch the event down, find a child  // who can handle it, start with the front-most child.  final int scrolledXInt = (int) scrolledXFloat;  final int scrolledYInt = (int) scrolledYFloat;  final View[] children = mChildren;  final int count = mChildrenCount;  for (int i = count - 1; i >= 0; i--)        // 2、迭代所有子view,查找触摸事件在哪个子view的坐标范围内  final View child = children[i];  // 该child是可见的  if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE  || child.getAnimation() != null) {  // 3、获取child的坐标范围  child.getHitRect(frame);                 // 4、判断发生该事件坐标是否在该child坐标范围内  if (frame.contains(scrolledXInt, scrolledYInt))      // offset the event to the view's coordinate system  final float xc = scrolledXFloat - child.mLeft;  final float yc = scrolledYFloat - child.mTop;  ev.setLocation(xc, yc);  child.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  // 5、child处理该事件,如果返回true,那么mMotionTarget为该child。正常情况下,  // dispatchTouchEvent(ev)的返回值即onTouchEcent的返回值。因此onTouchEcent如果返回为true,  // 那么mMotionTarget为触摸事件所在位置的child。  if (child.dispatchTouchEvent(ev))       // 6、 mMotionTarget为该childmMotionTarget = child;  return true;  }  }  }  }  }  }// end if  boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) ||  (action == MotionEvent.ACTION_CANCEL);  if (isUpOrCancel) {  // Note, we've already copied the previous state to our local  // variable, so this takes effect on the next event  mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;  }  // 触摸事件的目标view, 即触摸所在的viewfinal View target = mMotionTarget;  // 7、如果mMotionTarget为空,那么执行super.super.dispatchTouchEvent(ev),  // 即View.dispatchTouchEvent(ev),就是该View Group自己处理该touch事件,只是又走了一遍View的分发过程而已.  // 拦截事件或者在不拦截事件且target view的onTouchEvent返回false的情况都会执行到这一步.  if (target == null) {  // We don't have a target, this means we're handling the  // event as a regular view.  ev.setLocation(xf, yf);  if ((mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {  ev.setAction(MotionEvent.ACTION_CANCEL);  mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  }  return super.dispatchTouchEvent(ev);  }  // 8、如果没有禁用事件拦截,并且onInterceptTouchEvent(ev)返回为true,即进行事件拦截.  ( 似乎总走不到这一步 ??? )  if (!disallowIntercept && onInterceptTouchEvent(ev)) {  final float xc = scrolledXFloat - (float) target.mLeft;  final float yc = scrolledYFloat - (float) target.mTop;  mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  ev.setAction(MotionEvent.ACTION_CANCEL);  ev.setLocation(xc, yc);  //   if (!target.dispatchTouchEvent(ev)) {  // target didn't handle ACTION_CANCEL. not much we can do  // but they should have.  }  // clear the target  mMotionTarget = null;  // Don't dispatch this event to our own view, because we already  // saw it when intercepting; we just want to give the following  // event to the normal onTouchEvent().  return true;  }  if (isUpOrCancel) {  mMotionTarget = null;  }  // finally offset the event to the target's coordinate system and  // dispatch the event.  final float xc = scrolledXFloat - (float) target.mLeft;  final float yc = scrolledYFloat - (float) target.mTop;  ev.setLocation(xc, yc);  if ((target.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {  ev.setAction(MotionEvent.ACTION_CANCEL);  target.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  mMotionTarget = null;  }  // 9、事件不拦截,且target view在ACTION_DOWN时返回true,那么后续事件由target来处理事件  return target.dispatchTouchEvent(ev);
}

如果不对事件进来拦截,且TouchTv对事件的处理返回true,那么在DOWN事件时,mMotionTarget就是TouchTv,后续的事件就会通过注释9来处理,即直接交给TouvhTv来处理。如果在DOWN时就拦截事件,那么mMotionTarget为空,则会执行注释7出的代码,一直调用super.dispatchTouchEvent处理事件,即调用本类的事件处理,最终会调用onTouchEvent方法。如果在DOWN时不拦截,MOVE时拦截,那么会引发注释8的代码,target view收到一个cancel事件,且mMotionTarget被置空,后续事件在注释7出的代理进行处理,即在自己的onTouchEvent中进行处理。

Android触摸事件分发相关推荐

  1. android触摸事件分发,Android 事件分发机制

    Android 事件分发机制一直让人头痛,之前也是面向 GitHub 编程得过且过.今天下定决心了解一下,以便后面自己定制 View 效果.Android 触摸事件有三个基本类型:ACTION_DOW ...

  2. 为了讲清楚Android触摸事件,我“拆了部手机”

    Android 是一个有用户界面(GUI)的操作系统,在它诞生之初,就是为带有触摸屏的手持设备准备的.作为提供给用户最重要的交互方式之一,了解触摸系统是怎么工作的,对于实际的项目开发有着非常大的帮助. ...

  3. android 抽屉侧滑冲突,利用DrawerLayout和触摸事件分发实现抽屉侧滑效果

    本文实例为大家分享了DrawerLayout和触摸事件分发实现抽屉侧滑效果的具体代码,供大家参考,具体内容如下 效果展示 还是看代码实在,直接上菜了. 1.MainActivity的代码: publi ...

  4. Android的事件分发

    1. Touch事件和绘制事件的异同之处 Touch事件和绘制事件很类似,都是由ViewRoot派发下来的,但是不同之处在绘制事件是由应用中的某个View发起请求,一层一层上传到ViewRoot,再有 ...

  5. Android 系统(218)---Android的事件分发机制以及滑动冲突的解决

    Android的事件分发机制以及滑动冲突的解决 声明:  本文主要涉及VIew的事件分发与滑动冲突的解决,关于View的事件分发流程的部分内容参考自:  Android事件分发机制详解:史上最全面.最 ...

  6. Android的事件分发机制

    前言 Android事件分发机制是Android开发者必须了解的基础 网上有大量关于Android事件分发机制的文章,但存在一些问题:内容不全.思路不清晰.无源码分析.简单问题复杂化等等 今天,我将把 ...

  7. android SDK-25事件分发机制--源码正确解析

    android SDK-25事件分发机制–源码正确解析 Android 事件分发分为View和ViewGroup的事件分发,ViewGroup比View过一个拦截判断,viewgroup可以拦截事件, ...

  8. Android 触摸事件(Touch)的传递机制

    Touch 事件的传递机制 一个完整的touch 事件,由一个 down 事件.n 个 move 事件,一个 up 事件组成. Touch 事 件 一 般 的 传 递 流 程 Activity--&g ...

  9. Android触摸事件传递分析与实践

    设计UI时,亲爱的交互设计师们总会有一些天马行空的想法,大多数情况下原生的控件已不能支持这些"看似简单"的交互逻辑,需要继承ListView.ViewPager.ScrollVie ...

最新文章

  1. 网站建设中购买虚拟主机重要参数有哪些?
  2. 青龙羊毛——果园合集(快手+抖音)(教程)
  3. mysql数据库array_mysql数据库array
  4. java文件file字符集_获取文件字符集(或文件编码) 的工具类
  5. ABAQUS用户子程序一览表
  6. python获取网页元素坐标_Python实战爬虫系统学习笔记一:解析网页中的元素
  7. 如何解压缩.7z 001,.7z002....
  8. mysql搜索所有表,mySQL查询来搜索数据库中的所有表以查找字符串?
  9. 搭建 Apache Jmeter 分布式压测与监控
  10. 使用JIRA搭建本地项目管理工具
  11. 关于日期插件在chrome中出现被遮挡的问题
  12. 格式工厂怎么将qlv转换成mp4 转换方法最新
  13. 增大mysql修改表空间_扩充数据库表空间
  14. windows正版系统下载地址
  15. unity 角色鉴赏 spine动画鉴赏人物
  16. Github优秀作品
  17. Lunix基础终端控制器操作
  18. 优酷youku 1080P 视频下载方法
  19. Google首席决策师告诉你AI和数据科学团队需要哪10种角色?
  20. python简笔画教程视频_只用C++和Python,让你的简笔画实时动起来!

热门文章

  1. 人工智能、机器学习、机器人之间有什么区别和联系?(楚才国科)
  2. 智能优化算法(Ga,PSO,SA)高度模块化(可直接调用)python实现
  3. Windows程式开发设计指南(二十)多工和多执行绪
  4. 基于深度学习的表情识别系统(中英文版本)
  5. 【新手向】Unity 2020 + SteamVR 2.x 基础知识
  6. 测试中出现ERROR StatusLogger No log4j2 configuration file
  7. 绘制tRNAscan-SE生成的二级结构
  8. Linux proc详解
  9. 从放弃本专业,到直播编程,这女孩如何做到的?
  10. 【CubeMX配置STM32使用360°旋转编码器(KY-040)】