android 事件分发机制

来源:互联网 发布:淘宝怎么买电话轰炸 编辑:程序博客网 时间:2024/04/30 18:00

前段时间做项目的时候,碰见listview上的button点击总是没有效果的问题,以及一些自定义组合空间点击木有相应,或者是响应的结果不对。当时只是在网上搜了些解决的办法,很乱。嘿嘿,现在想起来真的的好傻。最近拜读了两篇大神的文章讲解android事件分发机制的,自己mark一下,防止遗忘,同时方便以后查找。

        事件分发主要分为两部分:view的事件分发viewgroup的事件分发。在探讨事件分发机制之前,先需要搞清楚android两个基础控件view和viewgroup,以及它们之间的关系:view是没有子控件的,像button,textview都是view控件。而viewgroup继承自view,是可以存在子控件的。也就是说viewgroup就是一组view或者是viewroup的集合,它是所有页面布局的父类(eg linearlayout,relativelayout) 

       1.view的事件分发:  dsipatchTouchEvent 方法:事件分发 和 onTouchEvent方法:事件消费

先做一个小例子,显示下事件分发和消费的过程:

自定义一个CustomButton,并重写dsipatchTouchEvent 和onTouchEvent:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.example.motioneventdispatchtest;  
  2.   
  3. import android.content.Context;  
  4. import android.util.AttributeSet;  
  5. import android.util.Log;  
  6. import android.view.MotionEvent;  
  7. import android.widget.Button;  
  8.   
  9. public class CustomButton extends Button {  
  10.   
  11.     private static final String TAG = "MotionEventDispatch";  
  12.   
  13.     public CustomButton(Context context, AttributeSet attrs) {  
  14.         super(context, attrs);  
  15.     }  
  16.   
  17.     // 位于textview里面  
  18.     @Override  
  19.     public boolean onTouchEvent(MotionEvent event) {  
  20.         switch (event.getAction()) {  
  21.         case MotionEvent.ACTION_DOWN:  
  22.             Log.i(TAG, "CustomButton-onTouchEvent-ACTION_DOWN");  
  23.             break;  
  24.         case MotionEvent.ACTION_UP:  
  25.             Log.i(TAG, "CustomButton-onTouchEvent-ACTION_UP");  
  26.             break;  
  27.         default:  
  28.             break;  
  29.         }  
  30.         return super.onTouchEvent(event);  
  31.     }  
  32.   
  33.     // 位于view里面  
  34.     @Override  
  35.     public boolean dispatchTouchEvent(MotionEvent event) {  
  36.         switch (event.getAction()) {  
  37.         case MotionEvent.ACTION_DOWN:  
  38.             Log.i(TAG, "CustomButton-dispatchTouchEvent-ACTION_DOWN");  
  39.             break;  
  40.         case MotionEvent.ACTION_UP:  
  41.             Log.i(TAG, "CustomButton-dispatchTouchEvent-ACTION_UP");  
  42.             break;  
  43.         default:  
  44.             break;  
  45.         }  
  46.         return super.dispatchTouchEvent(event);  
  47.     }  
  48.   
  49. }  

然后在MainActivity中监听注册click监听和touch监听,并且重写activity的dsipatchTouchEvent 和onTouchEvent:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.example.motioneventdispatchtest;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.util.Log;  
  6. import android.view.Menu;  
  7. import android.view.MotionEvent;  
  8. import android.view.View;  
  9. public class MainActivity extends Activity {  
  10.   
  11.     private static final String TAG = "MotionEventDispatch";  
  12.     private CustomButton button;  
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.activity_main);  
  17.         button = (CustomButton)findViewById(R.id.button1);  
  18.           
  19.         button.setOnClickListener(new View.OnClickListener() {  
  20.               
  21.             @Override  
  22.             public void onClick(View arg0) {  
  23.                 Log.i(TAG, "CustomButton--onClick");  
  24.                   
  25.             }  
  26.         });  
  27.           
  28.         button.setOnTouchListener(new View.OnTouchListener() {  
  29.               
  30.             @Override  
  31.             public boolean onTouch(View v, MotionEvent event) {  
  32.                 switch (event.getAction()) {  
  33.                 case MotionEvent.ACTION_DOWN:  
  34.                     Log.i(TAG, "CustomButton-onTouch-ACTION_DOWN");  
  35.                     break;  
  36.                 case MotionEvent.ACTION_UP:  
  37.                     Log.i(TAG, "CustomButton-onTouch-ACTION_UP");  
  38.                     break;  
  39.                 default:  
  40.                     break;  
  41.                 }  
  42.                 return false;  
  43.             }  
  44.         });  
  45.     }  
  46.   
  47.       
  48.     @Override  
  49.     public boolean dispatchTouchEvent(MotionEvent ev) {  
  50.         switch (ev.getAction()) {  
  51.         case MotionEvent.ACTION_DOWN:  
  52.             Log.i(TAG, "MainActivity-dispatchTouchEvent-ACTION_DOWN");  
  53.             break;  
  54.         case MotionEvent.ACTION_UP:  
  55.             Log.i(TAG, "MainActivity-dispatchTouchEvent-ACTION_UP");  
  56.             break;  
  57.         default:  
  58.             break;  
  59.         }  
  60.         return super.dispatchTouchEvent(ev);  
  61.     }  
  62.   
  63.   
  64.     @Override  
  65.     public boolean onTouchEvent(MotionEvent event) {  
  66.         switch (event.getAction()) {  
  67.         case MotionEvent.ACTION_DOWN:  
  68.             Log.i(TAG, "MainActivity-onTouchEvent-ACTION_DOWN");  
  69.             break;  
  70.         case MotionEvent.ACTION_UP:  
  71.             Log.i(TAG, "MainActivity-onTouchEvent-ACTION_UP");  
  72.             break;  
  73.         default:  
  74.             break;  
  75.         }  
  76.         return super.onTouchEvent(event);  
  77.     }  
  78.   
  79.   
  80.     @Override  
  81.     public boolean onCreateOptionsMenu(Menu menu) {  
  82.         // Inflate the menu; this adds items to the action bar if it is present.  
  83.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  84.         return true;  
  85.     }  
  86.   
  87. }  

布局文件:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <com.example.motioneventdispatchtest.CustomButton  
  8.         android:id="@+id/button1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_alignParentTop="true"  
  12.         android:layout_centerHorizontal="true"  
  13.         android:layout_marginTop="171dp" />  
  14. </RelativeLayout>  

点击button之后,log如下:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. 05-22 00:15:28.905: I/MotionEventDispatch(22044): MainActivity-dispatchTouchEvent-ACTION_DOWN  
  2. 05-22 00:15:28.908: I/MotionEventDispatch(22044): CustomButton-dispatchTouchEvent-ACTION_DOWN  
  3. 05-22 00:15:28.908: I/MotionEventDispatch(22044): CustomButton-onTouch-ACTION_DOWN  
  4. 05-22 00:15:28.909: I/MotionEventDispatch(22044): CustomButton-onTouchEvent-ACTION_DOWN  
  5. 05-22 00:15:28.969: I/MotionEventDispatch(22044): MainActivity-dispatchTouchEvent-ACTION_UP  
  6. 05-22 00:15:28.969: I/MotionEventDispatch(22044): CustomButton-dispatchTouchEvent-ACTION_UP  
  7. 05-22 00:15:28.971: I/MotionEventDispatch(22044): CustomButton-onTouch-ACTION_UP  
  8. 05-22 00:15:28.971: I/MotionEventDispatch(22044): CustomButton-onTouchEvent-ACTION_UP  
  9. 05-22 00:15:28.975: I/MotionEventDispatch(22044): CustomButton--onClick  

过程如下:touch down事件首先由activity的dsipatchTouchEvent 进行分发,接着道CustomButton的dsipatchTouchEvent 进行分发,然后执行CustomButton的onTouch,接着是onTouchEvent。up的时候顺序是相同的,最后执行了onTouchEvent里面的onclick方法。结果为什么会是这样的呢,下面从源代码的角度进行分析:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public boolean dispatchTouchEvent(MotionEvent event) {  
  2.     if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&  
  3.             mOnTouchListener.onTouch(this, event)) {  
  4.         return true;  
  5.     }  
  6.     return onTouchEvent(event);  
  7. }  

mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && mOnTouchListener.onTouch(this, event)如果这三个条件都为真,就返回true,否则的话就去执行onTouchEvent(event)并返回结果。

第一个条件:mOnTouchListener != null,只要控件注册了touch事件,mOnTouchListener 就会被赋值不为空,代码为证:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public void setOnTouchListener(OnTouchListener l) {  
  2.     mOnTouchListener = l;  
  3. }  

第二个条件: (mViewFlags & ENABLED_MASK) == ENABLED,一般的控件都是enabled的吧,所以这个也是true咯

第三个条件:mOnTouchListener.onTouch(this, event),这里是回调touch注册事件里面的onTouch方法,如果onTouch返回true则dsipatchTouchEvent 也会返回true;如果onTouch方法返回false,则会再去执行onTouchEvent方法。

这里可以看出dsipatchTouchEvent 中onTouch和onTouchEvent方法都会被执行,最先执行的是onTouc,所以也就解释了为什么打印出来的log中onTouch比onclick要先出现咯,现在也仅仅是解释了这个。既然oclick事件被执行了,那么就肯定是在onTouchEvent方法里面被执行的,嘿嘿。

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public boolean onTouchEvent(MotionEvent event) {  
  2.     final int viewFlags = mViewFlags;  
  3.     if ((viewFlags & ENABLED_MASK) == DISABLED) {  
  4.         // A disabled view that is clickable still consumes the touch  
  5.         // events, it just doesn't respond to them.  
  6.         return (((viewFlags & CLICKABLE) == CLICKABLE ||  
  7.                 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));  
  8.     }  
  9.     if (mTouchDelegate != null) {  
  10.         if (mTouchDelegate.onTouchEvent(event)) {  
  11.             return true;  
  12.         }  
  13.     }  
  14.     if (((viewFlags & CLICKABLE) == CLICKABLE ||  
  15.             (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {  
  16.         switch (event.getAction()) {  
  17.             case MotionEvent.ACTION_UP:  
  18.                 boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;  
  19.                 if ((mPrivateFlags & PRESSED) != 0 || prepressed) {  
  20.                     // take focus if we don't have it already and we should in  
  21.                     // touch mode.  
  22.                     boolean focusTaken = false;  
  23.                     if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {  
  24.                         focusTaken = requestFocus();  
  25.                     }  
  26.                     if (!mHasPerformedLongPress) {  
  27.                         // This is a tap, so remove the longpress check  
  28.                         removeLongPressCallback();  
  29.                         // Only perform take click actions if we were in the pressed state  
  30.                         if (!focusTaken) {  
  31.                             // Use a Runnable and post this rather than calling  
  32.                             // performClick directly. This lets other visual state  
  33.                             // of the view update before click actions start.  
  34.                             if (mPerformClick == null) {  
  35.                                 mPerformClick = new PerformClick();  
  36.                             }  
  37.                             if (!post(mPerformClick)) {  
  38.                                 performClick();  
  39.                             }  
  40.                         }  
  41.                     }  
  42.                     if (mUnsetPressedState == null) {  
  43.                         mUnsetPressedState = new UnsetPressedState();  
  44.                     }  
  45.                     if (prepressed) {  
  46.                         mPrivateFlags |= PRESSED;  
  47.                         refreshDrawableState();  
  48.                         postDelayed(mUnsetPressedState,  
  49.                                 ViewConfiguration.getPressedStateDuration());  
  50.                     } else if (!post(mUnsetPressedState)) {  
  51.                         // If the post failed, unpress right now  
  52.                         mUnsetPressedState.run();  
  53.                     }  
  54.                     removeTapCallback();  
  55.                 }  
  56.                 break;  
  57.             case MotionEvent.ACTION_DOWN:  
  58.                 if (mPendingCheckForTap == null) {  
  59.                     mPendingCheckForTap = new CheckForTap();  
  60.                 }  
  61.                 mPrivateFlags |= PREPRESSED;  
  62.                 mHasPerformedLongPress = false;  
  63.                 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());  
  64.                 break;  
  65.             case MotionEvent.ACTION_CANCEL:  
  66.                 mPrivateFlags &= ~PRESSED;  
  67.                 refreshDrawableState();  
  68.                 removeTapCallback();  
  69.                 break;  
  70.             case MotionEvent.ACTION_MOVE:  
  71.                 final int x = (int) event.getX();  
  72.                 final int y = (int) event.getY();  
  73.                 // Be lenient about moving outside of buttons  
  74.                 int slop = mTouchSlop;  
  75.                 if ((x < 0 - slop) || (x >= getWidth() + slop) ||  
  76.                         (y < 0 - slop) || (y >= getHeight() + slop)) {  
  77.                     // Outside button  
  78.                     removeTapCallback();  
  79.                     if ((mPrivateFlags & PRESSED) != 0) {  
  80.                         // Remove any future long press/tap checks  
  81.                         removeLongPressCallback();  
  82.                         // Need to switch from pressed to not pressed  
  83.                         mPrivateFlags &= ~PRESSED;  
  84.                         refreshDrawableState();  
  85.                     }  
  86.                 }  
  87.                 break;  
  88.         }  
  89.         return true;  
  90.     }  
  91.     return false;  
  92. }  

代码最终会进入performClick方法中,代码如下:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public boolean performClick() {  
  2.     sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);  
  3.     if (mOnClickListener != null) {  
  4.         playSoundEffect(SoundEffectConstants.CLICK);  
  5.         mOnClickListener.onClick(this);  
  6.         return true;  
  7.     }  
  8.     return false;  
  9. }  

这里只要mOnClickListener不为空,就会触发onClick事件,而mOnClickListener则会在setOnClickListener当中被赋值。

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public void setOnClickListener(OnClickListener l) {  
  2.     if (!isClickable()) {  
  3.         setClickable(true);  
  4.     }  
  5.     mOnClickListener = l;  
  6. }  

现在对上了吧,就是在onTouchEvent方法里面执行了注册的onclick监听,所以整个流程是通了。

现在来总结一下为什么上面打印的log是那样子的:touch事件的入口是dsipatchTouchEvent ,首先执行注册的onTouch监听,如果返回的结果是false,就会接着执行onTouchEvent。在执行onTouchEvent的时候,会执行onClick监听,这样就解释清楚了打印的顺序。在dsipatchTouchEvent 进行事件分发的时候,一旦返回true,就表示该事件已经被消费了处理了,不会再继续往下传了。如果onTouch返回true,那么它dsipatchTouchEvent 就会返回true,表示事件已被处理。不会去执行onTouchEvent了,也就更不会去处理onclick监听了。这里我们改一下上面的例子,看下打印出来的结果哈:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. 05-22 01:25:19.918: I/MotionEventDispatch(25626): MainActivity-dispatchTouchEvent-ACTION_DOWN  
  2. 05-22 01:25:19.919: I/MotionEventDispatch(25626): CustomButton-dispatchTouchEvent-ACTION_DOWN  
  3. 05-22 01:25:19.919: I/MotionEventDispatch(25626): CustomButton-onTouch-ACTION_DOWN  
  4. 05-22 01:25:19.996: I/MotionEventDispatch(25626): MainActivity-dispatchTouchEvent-ACTION_UP  
  5. 05-22 01:25:19.996: I/MotionEventDispatch(25626): CustomButton-dispatchTouchEvent-ACTION_UP  
  6. 05-22 01:25:19.996: I/MotionEventDispatch(25626): CustomButton-onTouch-ACTION_UP  

是不是onTouchEvent就没有执行了哇。


这里有一个很重要的知识点,是在一个大牛的文章上看到的,受益匪浅,在这里引用一下,像郭霖大侠致敬:

http://blog.csdn.net/guolin_blog/article/details/9097463

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. 就是touch事件的层级传递。我们都知道如果给一个控件注册了touch事件,每次点击它的时候都会触发一系列的ACTION_DOWN,ACTION_MOVE,ACTION_UP等事件。这里需要注意,如果你在执行ACTION_DOWN的时候返回了false,后面一系列其它的action就不会再得到执行了。简单的说,就是当dispatchTouchEvent在进行事件分发的时候,只有前一个action返回true,才会触发后一个action。  
  2. 说到这里,很多的朋友肯定要有巨大的疑问了。这不是在自相矛盾吗?前面的例子中,明明在onTouch事件里面返回了false,ACTION_DOWN和ACTION_UP不是都得到执行了吗?其实你只是被假象所迷惑了,让我们仔细分析一下,在前面的例子当中,我们到底返回的是什么。  
  3. 参考着我们前面分析的源码,首先在onTouch事件里返回了false,就一定会进入到onTouchEvent方法中,然后我们来看一下onTouchEvent方法的细节。由于我们点击了按钮,就会进入到第14行这个if判断的内部,然后你会发现,不管当前的action是什么,最终都一定会走到第89行,返回一个true。  
  4. 是不是有一种被欺骗的感觉?明明在onTouch事件里返回了false,系统还是在onTouchEvent方法中帮你返回了true。就因为这个原因,才使得前面的例子中ACTION_UP可以得到执行。  
[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. 那我们可以换一个控件,将按钮替换成ImageView,然后给它也注册一个touch事件,并返回false。如下所示:  
  2.   
  3. [java] view plaincopy  
  4. imageView.setOnTouchListener(new OnTouchListener() {    
  5.     @Override    
  6.     public boolean onTouch(View v, MotionEvent event) {    
  7.         Log.d("TAG", "onTouch execute, action " + event.getAction());    
  8.         return false;    
  9.     }    
  10. });    
  11. 运行一下程序,点击ImageView,你会发现结果如下:  
  12.   
  13.   
  14. 在ACTION_DOWN执行完后,后面的一系列action都不会得到执行了。这又是为什么呢?因为ImageView和按钮不同,它是默认不可点击的,因此在onTouchEvent的第14行判断时无法进入到if的内部,直接跳到第91行返回了false,也就导致后面其它的action都无法执行了。  

 2.viewGroup的事件分发:  dsipatchTouchEvent 方法:事件分发 和 onTouchEvent方法:事件消费  onInterceptTouchevent:事件拦截

相比较view而言,多了一个onInterceptTouchevent函数,那么它的作用是什么勒,看过另一篇文章,觉得它的比喻比较恰当和形象:onInterceptTouchevent就相当于viewgroup的一个管家,家庭秘书。为什么view没有呢,因为它没有子控件,用不着啊。一个touch事件来了,onInterceptTouchevent函数就负责判断决定是viewgroup自己消费处理呢,还是传递给它的孩子进行消费处理。

还是先弄一个demo吧,首先自定义一个layout:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.example.motioneventdispatchtest;  
  2.   
  3. import android.content.Context;  
  4. import android.util.AttributeSet;  
  5. import android.util.Log;  
  6. import android.view.MotionEvent;  
  7. import android.widget.LinearLayout;  
  8.   
  9. public class CustomLayout extends LinearLayout {  
  10.     private final static String TAG = "MotionEventDispatch";  
  11.   
  12.     public CustomLayout(Context context, AttributeSet attrs) {  
  13.         super(context, attrs);  
  14.         // TODO Auto-generated constructor stub  
  15.     }  
  16.   
  17.     @Override  
  18.     public boolean onTouchEvent(MotionEvent event) {  
  19.         switch (event.getAction()) {  
  20.   
  21.         case MotionEvent.ACTION_DOWN:  
  22.   
  23.             Log.i(TAG, "CustomLayout-onTouchEvent-ACTION_DOWN");  
  24.             break;  
  25.         case MotionEvent.ACTION_UP:  
  26.             Log.i(TAG, "CustomLayout-onTouchEvent-ACTION_UP");  
  27.             break;  
  28.         default:  
  29.             break;  
  30.   
  31.         }  
  32.         return super.onTouchEvent(event);  
  33.     }  
  34.   
  35.     @Override  
  36.     public boolean dispatchTouchEvent(MotionEvent ev) {  
  37.         switch (ev.getAction()) {  
  38.   
  39.         case MotionEvent.ACTION_DOWN:  
  40.             Log.i(TAG, "CustomLayout-dispatchTouchEvent-ACTION_DOWN");  
  41.             break;  
  42.   
  43.         case MotionEvent.ACTION_UP:  
  44.             Log.i(TAG, "CustomLayout-dispatchTouchEvent-ACTION_UP");  
  45.             break;  
  46.   
  47.         default:  
  48.             break;  
  49.   
  50.         }  
  51.         return super.dispatchTouchEvent(ev);  
  52.     }  
  53.   
  54.     @Override  
  55.     public boolean onInterceptTouchEvent(MotionEvent ev) {  
  56.         switch (ev.getAction()) {  
  57.   
  58.         case MotionEvent.ACTION_DOWN:  
  59.             Log.i(TAG, "CustomLayout-onInterceptTouchEvent-ACTION_DOWN");  
  60.             break;  
  61.   
  62.         case MotionEvent.ACTION_UP:  
  63.             Log.i(TAG, "CustomLayout-onInterceptTouchEvent-ACTION_UP");  
  64.             break;  
  65.   
  66.         default:  
  67.             break;  
  68.   
  69.         }  
  70.         return super.onInterceptTouchEvent(ev);  
  71.     }  
  72.   
  73. }  


修改布局:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <com.example.motioneventdispatchtest.CustomLayout  
  8.         android:id="@+id/linearlayout_test"  
  9.         android:layout_width="200dip"  
  10.         android:layout_height="200dip" >  
  11.   
  12.         <com.example.motioneventdispatchtest.CustomButton  
  13.             android:id="@+id/button1"  
  14.             android:layout_width="wrap_content"  
  15.             android:layout_height="wrap_content"  
  16.             android:layout_alignParentTop="true"  
  17.             android:layout_centerHorizontal="true"  
  18.             android:layout_marginTop="171dp" />  
  19.     </com.example.motioneventdispatchtest.CustomLayout>  
  20.   
  21. </RelativeLayout>  


然后修改MainActivity,添加自定义layout的click和touch事件:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.example.motioneventdispatchtest;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.util.Log;  
  6. import android.view.Menu;  
  7. import android.view.MotionEvent;  
  8. import android.view.View;  
  9.   
  10. public class MainActivity extends Activity {  
  11.   
  12.     private static final String TAG = "MotionEventDispatch";  
  13.     private CustomButton button;  
  14.     private CustomLayout layout;  
  15.   
  16.     @Override  
  17.     protected void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.activity_main);  
  20.         button = (CustomButton) findViewById(R.id.button1);  
  21.         layout = (CustomLayout) findViewById(R.id.linearlayout_test);  
  22.         button.setOnClickListener(new View.OnClickListener() {  
  23.   
  24.             @Override  
  25.             public void onClick(View arg0) {  
  26.                 Log.i(TAG, "CustomButton--onClick");  
  27.   
  28.             }  
  29.         });  
  30.   
  31.         button.setOnTouchListener(new View.OnTouchListener() {  
  32.   
  33.             @Override  
  34.             public boolean onTouch(View v, MotionEvent event) {  
  35.                 switch (event.getAction()) {  
  36.                 case MotionEvent.ACTION_DOWN:  
  37.                     Log.i(TAG, "CustomButton-onTouch-ACTION_DOWN");  
  38.                     break;  
  39.                 case MotionEvent.ACTION_UP:  
  40.                     Log.i(TAG, "CustomButton-onTouch-ACTION_UP");  
  41.                     break;  
  42.                 default:  
  43.                     break;  
  44.                 }  
  45.                 return false;  
  46.             }  
  47.         });  
  48.   
  49.         layout.setOnClickListener(new View.OnClickListener() {  
  50.   
  51.             @Override  
  52.             public void onClick(View v) {  
  53.                 Log.i(TAG, "CustomLayout---onClick");  
  54.   
  55.             }  
  56.         });  
  57.   
  58.         layout.setOnTouchListener(new View.OnTouchListener() {  
  59.   
  60.             @Override  
  61.             public boolean onTouch(View v, MotionEvent event) {  
  62.                 switch (event.getAction()) {  
  63.   
  64.                 case MotionEvent.ACTION_DOWN:  
  65.                     Log.i(TAG, "CustomLayout-onTouch-ACTION_DOWN");  
  66.                     break;  
  67.                 case MotionEvent.ACTION_UP:  
  68.                     Log.i(TAG, "CustomLayout-onTouch-ACTION_UP");  
  69.                     break;  
  70.   
  71.                 default:  
  72.                     break;  
  73.   
  74.                 }  
  75.                 return false;  
  76.             }  
  77.         });  
  78.     }  
  79.   
  80.     @Override  
  81.     public boolean dispatchTouchEvent(MotionEvent ev) {  
  82.         switch (ev.getAction()) {  
  83.         case MotionEvent.ACTION_DOWN:  
  84.             Log.i(TAG, "MainActivity-dispatchTouchEvent-ACTION_DOWN");  
  85.             break;  
  86.         case MotionEvent.ACTION_UP:  
  87.             Log.i(TAG, "MainActivity-dispatchTouchEvent-ACTION_UP");  
  88.             break;  
  89.         default:  
  90.             break;  
  91.         }  
  92.         return super.dispatchTouchEvent(ev);  
  93.     }  
  94.   
  95.     @Override  
  96.     public boolean onTouchEvent(MotionEvent event) {  
  97.         switch (event.getAction()) {  
  98.         case MotionEvent.ACTION_DOWN:  
  99.             Log.i(TAG, "MainActivity-onTouchEvent-ACTION_DOWN");  
  100.             break;  
  101.         case MotionEvent.ACTION_UP:  
  102.             Log.i(TAG, "MainActivity-onTouchEvent-ACTION_UP");  
  103.             break;  
  104.         default:  
  105.             break;  
  106.         }  
  107.         return super.onTouchEvent(event);  
  108.     }  
  109.   
  110.     @Override  
  111.     public boolean onCreateOptionsMenu(Menu menu) {  
  112.         // Inflate the menu; this adds items to the action bar if it is present.  
  113.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  114.         return true;  
  115.     }  
  116.   
  117. }  

点击button的打印的log结果如下:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. 05-22 02:03:36.967: I/MotionEventDispatch(3045): MainActivity-dispatchTouchEvent-ACTION_DOWN  
  2. 05-22 02:03:36.967: I/MotionEventDispatch(3045): CustomLayout-dispatchTouchEvent-ACTION_DOWN  
  3. 05-22 02:03:36.967: I/MotionEventDispatch(3045): CustomLayout-onInterceptTouchEvent-ACTION_DOWN  
  4. 05-22 02:03:36.967: I/MotionEventDispatch(3045): CustomButton-dispatchTouchEvent-ACTION_DOWN  
  5. 05-22 02:03:36.967: I/MotionEventDispatch(3045): CustomButton-onTouch-ACTION_DOWN  
  6. 05-22 02:03:36.967: I/MotionEventDispatch(3045): CustomButton-onTouchEvent-ACTION_DOWN  
  7. 05-22 02:03:37.035: I/MotionEventDispatch(3045): MainActivity-dispatchTouchEvent-ACTION_UP  
  8. 05-22 02:03:37.035: I/MotionEventDispatch(3045): CustomLayout-dispatchTouchEvent-ACTION_UP  
  9. 05-22 02:03:37.036: I/MotionEventDispatch(3045): CustomLayout-onInterceptTouchEvent-ACTION_UP  
  10. 05-22 02:03:37.036: I/MotionEventDispatch(3045): CustomButton-dispatchTouchEvent-ACTION_UP  
  11. 05-22 02:03:37.036: I/MotionEventDispatch(3045): CustomButton-onTouch-ACTION_UP  
  12. 05-22 02:03:37.036: I/MotionEventDispatch(3045): CustomButton-onTouchEvent-ACTION_UP  
  13. 05-22 02:03:37.037: I/MotionEventDispatch(3045): CustomButton--onClick  


上面的log打印结果显示首先调用viewgroup的dispatchTouchEvent,然后执行viewgroup的onInterceptTouchEvent拦截事件,最后执行的是子控件view的disPatchTouchEvent,剩下就和view的事件分发逻辑是一样的咯,但是为什么会是这样子的呢?

viewgroup的dispatchTouchEvent源码:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public boolean dispatchTouchEvent(MotionEvent ev) {  
  2.     final int action = ev.getAction();  
  3.     final float xf = ev.getX();  
  4.     final float yf = ev.getY();  
  5.     final float scrolledXFloat = xf + mScrollX;  
  6.     final float scrolledYFloat = yf + mScrollY;  
  7.     final Rect frame = mTempRect;  
  8.     boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;  
  9.     if (action == MotionEvent.ACTION_DOWN) {  
  10.         if (mMotionTarget != null) {  
  11.             mMotionTarget = null;  
  12.         }  
  13.         if (disallowIntercept || !onInterceptTouchEvent(ev)) {  
  14.             ev.setAction(MotionEvent.ACTION_DOWN);  
  15.             final int scrolledXInt = (int) scrolledXFloat;  
  16.             final int scrolledYInt = (int) scrolledYFloat;  
  17.             final View[] children = mChildren;  
  18.             final int count = mChildrenCount;  
  19.             for (int i = count - 1; i >= 0; i--) {  
  20.                 final View child = children[i];  
  21.                 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE  
  22.                         || child.getAnimation() != null) {  
  23.                     child.getHitRect(frame);  
  24.                     if (frame.contains(scrolledXInt, scrolledYInt)) {  
  25.                         final float xc = scrolledXFloat - child.mLeft;  
  26.                         final float yc = scrolledYFloat - child.mTop;  
  27.                         ev.setLocation(xc, yc);  
  28.                         child.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  
  29.                         if (child.dispatchTouchEvent(ev))  {  
  30.                             mMotionTarget = child;  
  31.                             return true;  
  32.                         }  
  33.                     }  
  34.                 }  
  35.             }  
  36.         }  
  37.     }  
  38.     boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) ||  
  39.             (action == MotionEvent.ACTION_CANCEL);  
  40.     if (isUpOrCancel) {  
  41.         mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;  
  42.     }  
  43.     final View target = mMotionTarget;  
  44.     if (target == null) {  
  45.         ev.setLocation(xf, yf);  
  46.         if ((mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {  
  47.             ev.setAction(MotionEvent.ACTION_CANCEL);  
  48.             mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  
  49.         }  
  50.         return super.dispatchTouchEvent(ev);  
  51.     }  
  52.     if (!disallowIntercept && onInterceptTouchEvent(ev)) {  
  53.         final float xc = scrolledXFloat - (float) target.mLeft;  
  54.         final float yc = scrolledYFloat - (float) target.mTop;  
  55.         mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  
  56.         ev.setAction(MotionEvent.ACTION_CANCEL);  
  57.         ev.setLocation(xc, yc);  
  58.         if (!target.dispatchTouchEvent(ev)) {  
  59.         }  
  60.         mMotionTarget = null;  
  61.         return true;  
  62.     }  
  63.     if (isUpOrCancel) {  
  64.         mMotionTarget = null;  
  65.     }  
  66.     final float xc = scrolledXFloat - (float) target.mLeft;  
  67.     final float yc = scrolledYFloat - (float) target.mTop;  
  68.     ev.setLocation(xc, yc);  
  69.     if ((target.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {  
  70.         ev.setAction(MotionEvent.ACTION_CANCEL);  
  71.         target.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  
  72.         mMotionTarget = null;  
  73.     }  
  74.     return target.dispatchTouchEvent(ev);  
  75. }  


 onInterceptTouchEvent源码;

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /**  
  2.  * Implement this method to intercept all touch screen motion events.  This  
  3.  * allows you to watch events as they are dispatched to your children, and  
  4.  * take ownership of the current gesture at any point.  
  5.  *  
  6.  * <p>Using this function takes some care, as it has a fairly complicated  
  7.  * interaction with {@link View#onTouchEvent(MotionEvent)  
  8.  * View.onTouchEvent(MotionEvent)}, and using it requires implementing  
  9.  * that method as well as this one in the correct way.  Events will be  
  10.  * received in the following order:  
  11.  *  
  12.  * <ol>  
  13.  * <li> You will receive the down event here.  
  14.  * <li> The down event will be handled either by a child of this view  
  15.  * group, or given to your own onTouchEvent() method to handle; this means  
  16.  * you should implement onTouchEvent() to return true, so you will  
  17.  * continue to see the rest of the gesture (instead of looking for  
  18.  * a parent view to handle it).  Also, by returning true from  
  19.  * onTouchEvent(), you will not receive any following  
  20.  * events in onInterceptTouchEvent() and all touch processing must  
  21.  * happen in onTouchEvent() like normal.  
  22.  * <li> For as long as you return false from this function, each following  
  23.  * event (up to and including the final up) will be delivered first here  
  24.  * and then to the target's onTouchEvent().  
  25.  * <li> If you return true from here, you will not receive any  
  26.  * following events: the target view will receive the same event but  
  27.  * with the action {@link MotionEvent#ACTION_CANCEL}, and all further  
  28.  * events will be delivered to your onTouchEvent() method and no longer  
  29.  * appear here.  
  30.  * </ol>  
  31.  *  
  32.  * @param ev The motion event being dispatched down the hierarchy.  
  33.  * @return Return true to steal motion events from the children and have  
  34.  * them dispatched to this ViewGroup through onTouchEvent().  
  35.  * The current target will receive an ACTION_CANCEL event, and no further  
  36.  * messages will be delivered here.  
  37.  */  
  38. public boolean onInterceptTouchEvent(MotionEvent ev) {  
  39.     return false;  
  40. }  

源码解析,郭霖大牛的解析太好了,我就直接mark了:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. 这个方法代码比较长,我们只挑重点看。首先在第13行可以看到一个条件判断,如果disallowIntercept和!onInterceptTouchEvent(ev)两者有一个为true,就会进入到这个条件判断中。disallowIntercept是指是否禁用掉事件拦截的功能,默认是false,也可以通过调用requestDisallowInterceptTouchEvent方法对这个值进行修改。那么当第一个值为false的时候就会完全依赖第二个值来决定是否可以进入到条件判断的内部,第二个值是什么呢?竟然就是对onInterceptTouchEvent方法的返回值取反!也就是说如果我们在onInterceptTouchEvent方法中返回false,就会让第二个值为true,从而进入到条件判断的内部,如果我们在onInterceptTouchEvent方法中返回true,就会让第二个值为false,从而跳出了这个条件判断。  
  2.   
  3. 那我们重点来看下条件判断的内部是怎么实现的。在第19行通过一个for循环,遍历了当前ViewGroup下的所有子View,然后在第24行判断当前遍历的View是不是正在点击的View,如果是的话就会进入到该条件判断的内部,然后在第29行调用了该View的dispatchTouchEvent,之后的流程就和view的事件分发是一样的咯  


总结一下:

1.默认的onInterceptTouchEvent总是返回false的,就是不拦截touch事件,直接分发给了子控件。所以假如我们自定义了组合控件,譬如image+文字的组合控件,并且在activity里面注册监听期待点击它的时候会产生响应,那么我们就需要重写onInterceptTouchEvent了让它返回true,将事件拦截下来。

2.如果触摸的时候,我们只想出发ontouch监听,想屏蔽onclick监听的话,就需要在ontouch里面返回true就可以了

3.android事件分发是先传递到viewgroup,然后才传递到view的

4.子view如果将传递的事件消费处理掉,viewgroup当中是接收不到任何事件的

5.简单来讲,dispatchTouchEvent方法是为了onTouch监听的,onTouchEvent是为了onClick监听的。如果ontouch监听返回false,事件会传递到onTouchEvent当中触发onClick,如果是true的话就不会继续往下传递了。


0 0
原创粉丝点击