View工作原理(一)事件传递原理详解http://blog.csdn.net/ff20081528/article/details/17353869

一、准备知识

1、视图坐标与布局坐标的区别如下图所示:

	上图是一个坐标系,这个坐标系是无边无际的。这个无边无际的坐标系即视图坐标。手机屏幕可视范围内的坐标即手机屏幕的布局坐标(坐标原点是屏幕的左上方的(0,0)位置)即A点。屏幕里面的子视图里面可视范围内的坐标即子视图的布局坐标(坐标原点是子视图的左上方的(0,0)位置)即B点。
2、android中布局关系
 
二、例子说明事件分发过程
这里我写了一个布局文件,展示效果如上图。当我点击View1,事件的分发过程是这样的:
	1、ViewGroup3的dispatchTouchEvent()方法会被调用。
	2、ViewGroup3调用ViewGroup2的dispatchTouchEvent()方法。
	3、ViewGroup2调用ViewGroup1的dispatchTouchEvent()方法。
	4、ViewGroup1会调用View1的dispatchTouchEvent()方法。
	5、View1的dispatchTouchEvent()方法调用自己的onTouchEvent()方法。在onTouchEvent方法中处理点击事件。处理完了后会返回一个true给调用它的dispatchTouchEvent()方法。
	6、ViewGroup1的dispatchTouchEvent()方法会返回一个true值给ViewGroup2的dispatchTouchEvent()方法。这样一直将则个true值返回到ViewGroup3的dispatchTouchEvent()方法。ViewGroup3在将这个值返回给调用它的方法。这样一个事件分发过程结束。
转载请说明出处:http://blog.csdn.net/ff20081528/article/details/17353869
 
三、ViewGroup中处理消息的详细过程
	通过上面的列子对事件分发的过程有个大概的了解之后,我们通过ViewGroup中的dispatchTouchEvent()方法源码和View中的dispatchTouchEvent()方法及touchEvent方法源码来详细了解android是怎样处理这个过程的。
	ViewGroup中的dispatchTouchEvent()方法源码如下:
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2.     public boolean dispatchTouchEvent(MotionEvent ev) {  
  3.         if (!onFilterTouchEventForSecurity(ev)) {  
  4.             return false;  
  5.         }  
  6.   
  7.         final int action = ev.getAction();  
  8.         final float xf = ev.getX();  
  9.         final float yf = ev.getY();  
  10.         final float scrolledXFloat = xf + mScrollX;  
  11.         final float scrolledYFloat = yf + mScrollY;  
  12.         final Rect frame = mTempRect;  
  13.   
  14.         boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;  
  15.   
  16.         if (action == MotionEvent.ACTION_DOWN) {  
  17.             if (mMotionTarget != null) {  
  18.                 // this is weird, we got a pen down, but we thought it was  
  19.                 // already down!  
  20.                 // XXX: We should probably send an ACTION_UP to the current  
  21.                 // target.  
  22.                 mMotionTarget = null;  
  23.             }  
  24.             // If we're disallowing intercept or if we're allowing and we didn't  
  25.             // intercept  
  26.             if (disallowIntercept || !onInterceptTouchEvent(ev)) {  
  27.                 // reset this event's action (just to protect ourselves)  
  28.                 ev.setAction(MotionEvent.ACTION_DOWN);  
  29.                 // We know we want to dispatch the event down, find a child  
  30.                 // who can handle it, start with the front-most child.  
  31.                 final int scrolledXInt = (int) scrolledXFloat;  
  32.                 final int scrolledYInt = (int) scrolledYFloat;  
  33.                 final View[] children = mChildren;  
  34.                 final int count = mChildrenCount;  
  35.   
  36.                 for (int i = count - 1; i >= 0; i--) {  
  37.                     final View child = children[i];  
  38.                     if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE  
  39.                             || child.getAnimation() != null) {  
  40.                         child.getHitRect(frame);  
  41.                         if (frame.contains(scrolledXInt, scrolledYInt)) {  
  42.                             // offset the event to the view's coordinate system  
  43.                             final float xc = scrolledXFloat - child.mLeft;  
  44.                             final float yc = scrolledYFloat - child.mTop;  
  45.                             ev.setLocation(xc, yc);  
  46.                             child.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  
  47.                             if (child.dispatchTouchEvent(ev))  {  
  48.                                 // Event handled, we have a target now.  
  49.                                 mMotionTarget = child;  
  50.                                 return true;  
  51.                             }  
  52.                             // The event didn't get handled, try the next view.  
  53.                             // Don't reset the event's location, it's not  
  54.                             // necessary here.  
  55.                         }  
  56.                     }  
  57.                 }  
  58.             }  
  59.         }  
  60.   
  61.         boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) ||  
  62.                 (action == MotionEvent.ACTION_CANCEL);  
  63.   
  64.         if (isUpOrCancel) {  
  65.             // Note, we've already copied the previous state to our local  
  66.             // variable, so this takes effect on the next event  
  67.             mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;  
  68.         }  
  69.   
  70.         // The event wasn't an ACTION_DOWN, dispatch it to our target if  
  71.         // we have one.  
  72.         final View target = mMotionTarget;  
  73.         if (target == null) {  
  74.             // We don't have a target, this means we're handling the  
  75.             // event as a regular view.  
  76.             ev.setLocation(xf, yf);  
  77.             if ((mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {  
  78.                 ev.setAction(MotionEvent.ACTION_CANCEL);  
  79.                 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  
  80.             }  
  81.             return super.dispatchTouchEvent(ev);  
  82.         }  
  83.   
  84.         // if have a target, see if we're allowed to and want to intercept its  
  85.         // events  
  86.         if (!disallowIntercept && onInterceptTouchEvent(ev)) {  
  87.             final float xc = scrolledXFloat - (float) target.mLeft;  
  88.             final float yc = scrolledYFloat - (float) target.mTop;  
  89.             mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  
  90.             ev.setAction(MotionEvent.ACTION_CANCEL);  
  91.             ev.setLocation(xc, yc);  
  92.             if (!target.dispatchTouchEvent(ev)) {  
  93.                 // target didn't handle ACTION_CANCEL. not much we can do  
  94.                 // but they should have.  
  95.             }  
  96.             // clear the target  
  97.             mMotionTarget = null;  
  98.             // Don't dispatch this event to our own view, because we already  
  99.             // saw it when intercepting; we just want to give the following  
  100.             // event to the normal onTouchEvent().  
  101.             return true;  
  102.         }  
  103.   
  104.         if (isUpOrCancel) {  
  105.             mMotionTarget = null;  
  106.         }  
  107.   
  108.         // finally offset the event to the target's coordinate system and  
  109.         // dispatch the event.  
  110.         final float xc = scrolledXFloat - (float) target.mLeft;  
  111.         final float yc = scrolledYFloat - (float) target.mTop;  
  112.         ev.setLocation(xc, yc);  
  113.   
  114.         if ((target.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {  
  115.             ev.setAction(MotionEvent.ACTION_CANCEL);  
  116.             target.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;  
  117.             mMotionTarget = null;  
  118.         }  
  119.   
  120.         return target.dispatchTouchEvent(ev);  
  121.     }  

 

代码说明:

1、(代码2-4行)处理窗口处于模糊显示状态下的消息。所谓的模糊显示是指,应用程序可以设置当前窗口为模糊状态,此时窗口内部的所有视图将显示为模糊效果。这样的目的是为了隐藏窗口中的内容,对于其中的各个视图而言,可以设置改视图的FILTER_TOUCHERS_WHEN_OBSCURED标识,如存在该标识,则意味着用户希望不要处理该消息。
2、(代码6-11行)将ViewGroup的布局坐标转换成视图坐标。
3、(代码16-58行)处理ACTION_DOWN消息,其作用是判断该视图坐标落到了哪个子视图中。首先判断该ViewGroup本身是否被禁止获取TOUCH消息,如果没有禁止,并且回调函数onInterceptTouchEvent中没有消耗该消息,则开始寻找子视图。调用child.getHitRect(frame)方法获取该子视图在父视图中的布局坐标,即ViewGroup将child放在什么位置,这个位置相对于该child来讲是布局坐标,而对于该ViewGroup来讲却是视图坐标,参数frame是执行完毕后的位置输出矩形。得到位置后,就可以调用frame.contain()方法判断该消息位置是否被包含到了该child中,如果包含,并且该child也是一个ViewGroup,则准备递归调用该child的dispatchTouchEvent(),在调用之前,首先需要把坐标重新转换到child的坐标系中。接下来判断该child是否是ViewGroup类。如果是,则诋毁调用ViewGroupdispatchTouchEvent(),重新从第一步开始执行;如果child不是ViewGroup,而是一个View,则意味着诋毁调用的结束。

4、(代码61-68行)如果是ACTION_UP或者是ACTION_CANCEL消息,则清除mGroupFlags中的FLAG_DISALLOW_INTERCEPT标识,即允许该ViewGroup截获消息。也就是说,常见的情况就是当用户释放手指,下一次按下时,该ViewGroup本身可以重新截获消息,而在按下还没有释放期间,ViewGroup本身是不允许截获消息的。

5、(代码70-82)判断target变量是否为空。空代表了所有子窗口都没有消耗该消息,所以该ViewGroup本事需要处理该消息。然后还原消息的原始位置,将视图坐标重新转换成布局坐标,接着调用super.dispatchTouchEvent(ev),即View类的中的dispatchTouchEvent()方法(该方法会判断是否进行调用touchEvent()方法来处理,到后面的View类的源码中再介绍)。

6、(代码84-121)处理target存在,并且变量disallowInterceptfalse,即允许截获,在默认情况下ViewGroup都是允许截获消息的,只有当该ViewGroup的子视图调用父视图的requestDisallowdInterceptTouchEvent()方法时,方可禁止父视图再次截获消息,但每次ACTION_UP消息或者ACTION_CANCEL消息之后,该ViewGroup又会重新截获消息。ViewGroup本身不允许截获消息或者允许截获但是却没有消耗消息,于是调用target.dispatchTouchEvent(ev)方法把该消息继续交给目标视图处理,在调用该方法前需要检查target中是否申明过要取消随后的消息,即mPrivateFlags中包含 CANCEL_NEXT_UP_EVENT,如果是,则把消息action值修改为ACTION_CANCEL,将mMotionTarget变为空,因为target不想处理接下来的消息了,那么就可以认为没有target了。

 

四、View中处理消息的详细过程

dispatchTouchEvent()方法的源码

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.     * Pass the touch screen motion event down to the target view, or this 
  3.     * view if it is the target. 
  4.     * 
  5.     * @param event The motion event to be dispatched. 
  6.     * @return True if the event was handled by the view, false otherwise. 
  7.     */  
  8.    public boolean dispatchTouchEvent(MotionEvent event) {  
  9.        if (!onFilterTouchEventForSecurity(event)) {  
  10.            return false;  
  11.        }  
  12.   
  13.        if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&  
  14.                mOnTouchListener.onTouch(this, event)) {  
  15.            return true;  
  16.        }  
  17.        return onTouchEvent(event);  
  18.    }  

处理窗口处于模糊显示状态下的消息。然后回调视图监听着的onTouch()方法,如果监听者消耗了该消息,则直接返回。如果没有则调用ViewonTouchEvent()方法。

 

onTouchEvent()方法源码

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


1、代码10-15)处理该视图是否为disable状态,如果是,什么都不处理,返回true,即消耗该消息。

2、(代码17-21)消息代理处理消息。所谓的消息代理是指,可以给某个View指定一个消息处理代理,当View收到消息时,首先将该消息派发给其代理进行处理。如果代理内部消耗了该消息,则View不需要在进行任何处理;如果代理没有处理,则view继续处理。在这里不用多管,不会影响事件处理的逻辑和结果。

3、(代码22-102)判断该视图是否可以点击,如果不可以点击,则直接返回false,即不处理该消息。否则,真正开始执行触摸消息的默认处理逻辑,该逻辑分别处理了ACTION_DOWNACTION_MOVEACTION_UP消息.

(26-70)处理ACTION_UP消息,判断该UP消息是否发生在前面所讲的哪一个监测时间段中,并据此进行不同的处理。

(71-78)在ACTION_DOWN消息中,给mPrivateFlags变量添加PRESSED标识,并将变量mHasPerformLongPress设置为false,然后启动tap监测,即发送一个异步延迟消息。

对于触摸消息而言,消息本身没有repeat的属性,一次触摸只有一个ACTION_DOWN消息,按下来就是连续的ACTION_MOVE消息,并最终以处理ACTION_CANCEL消息.

(80-85)ACTION_CANCLE消息处理,这里只需清除PRESSED标识,刷新视图状态,然后再关闭tap监测即可。

(86-105)对ACTION_MOVE消息进行处理。具体逻辑包括,判断是否移动到了视图区域以外,如果是,则删除tap或者longPress的监测,并清除mPrivateFlags中的PRESSED标识,然后调用refreshDrawableState()刷新视图状态,这将导致对背景状态进行重绘。

 

 五、例子程序

通过代码可能完全理解事件的分发过程有点难,下面通过一个例子程序来巩固下事件分发的过程。

例子程序的UI如下:

布局如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <org.sunday.main.MyLinearLayout 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.     android:orientation="vertical" >  
  6.       
  7.      <org.sunday.main.MyLinearLayout  
  8.         android:id="@+id/ll2"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="100dp"  
  11.         android:background="@drawable/ll_selector"  
  12.         android:orientation="vertical" >  
  13.     </org.sunday.main.MyLinearLayout>  
  14.   
  15.     <org.sunday.main.MyLinearLayout  
  16.         android:id="@+id/ll1"  
  17.         android:layout_width="match_parent"  
  18.         android:layout_marginTop="20dp"  
  19.         android:layout_height="100dp"  
  20.         android:background="@drawable/ll_selector"  
  21.         android:orientation="vertical" >  
  22.   
  23.         <org.sunday.main.MyLinearLayout  
  24.             android:layout_width="80dp"  
  25.             android:layout_height="50dp"  
  26.             android:layout_marginTop="20dp"  
  27.             android:clickable="true"  
  28.             android:background="@drawable/ll_selector2"  
  29.             android:orientation="vertical" >  
  30.         </org.sunday.main.MyLinearLayout>  
  31.     </org.sunday.main.MyLinearLayout>  
  32.   
  33.     <org.sunday.main.MyLinearLayout  
  34.         android:id="@+id/ll3"  
  35.         android:layout_width="match_parent"  
  36.         android:layout_height="100dp"  
  37.         android:layout_marginTop="20dp"  
  38.         android:background="@drawable/ll_selector"  
  39.         android:orientation="vertical" >  
  40.   
  41.         <org.sunday.main.MyButton  
  42.             android:layout_width="wrap_content"  
  43.             android:layout_height="60dp"  
  44.             android:layout_margin="20dp"  
  45.             android:background="@drawable/btn_selector"  
  46.             android:text="button1" />  
  47.     </org.sunday.main.MyLinearLayout>  
  48.   
  49.     <org.sunday.main.MyLinearLayout  
  50.         android:id="@+id/ll4"  
  51.         android:layout_width="match_parent"  
  52.         android:layout_height="100dp"  
  53.         android:layout_marginTop="20dp"  
  54.         android:background="@drawable/ll_selector"  
  55.         android:orientation="vertical" >  
  56.   
  57.         <org.sunday.main.MyButtonWithOutEvent  
  58.             android:layout_width="wrap_content"  
  59.             android:layout_height="60dp"  
  60.             android:layout_margin="20dp"  
  61.             android:background="@drawable/btn_selector"  
  62.             android:text="button2" />  
  63.     </org.sunday.main.MyLinearLayout>  
  64.   
  65. </org.sunday.main.MyLinearLayout>  


MyLinearLayout.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package org.sunday.main;  
  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 MyLinearLayout extends LinearLayout {  
  10.     private final static String TAG = "MyLinearLayout";  
  11.   
  12.     public MyLinearLayout(Context context) {  
  13.         super(context);  
  14.     }  
  15.   
  16.     public MyLinearLayout(Context context, AttributeSet attrs) {  
  17.         super(context, attrs);  
  18.     }  
  19.       
  20.     @Override  
  21.     public boolean dispatchTouchEvent(MotionEvent ev) {  
  22.         Log.e(TAG, "dispatchTouchEvent()----------------" + this.toString());  
  23.         boolean isTrue = super.dispatchTouchEvent(ev);  
  24.         Log.e(TAG, "dispatchTouchEvent()  isTrue = " + isTrue + " --------------- ;"this.toString());  
  25.         return isTrue;  
  26.     }  
  27.       
  28.     @Override  
  29.     public boolean onTouchEvent(MotionEvent event) {  
  30.         Log.e(TAG, "onTouchEvent()----------------" + this.toString());  
  31.         boolean isTrue = super.onTouchEvent(event);  
  32.         Log.e(TAG, "onTouchEvent()  isTrue = " + isTrue+ "-----------------  ;"this.toString());  
  33.         return isTrue;  
  34.     }  
  35.       
  36. }  


MyButton.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package org.sunday.main;  
  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 MyButton extends Button {  
  10.     private final static String TAG = "MyButton";  
  11.   
  12.     public MyButton(Context context) {  
  13.         super(context);  
  14.     }  
  15.   
  16.     public MyButton(Context context, AttributeSet attrs) {  
  17.         super(context, attrs);  
  18.     }  
  19.   
  20.     @Override  
  21.     public boolean dispatchTouchEvent(MotionEvent event) {  
  22.         Log.e(TAG, "dispatchTouchEvent()----------------");  
  23.         boolean isTrue = super.dispatchTouchEvent(event);  
  24.         Log.e(TAG, "dispatchTouchEvent  isTrue = " + isTrue);  
  25.         return isTrue;  
  26.     }  
  27.       
  28.     @Override  
  29.     public boolean onTouchEvent(MotionEvent event) {  
  30.         Log.e(TAG, "onTouchEvent()----------------");  
  31.         boolean isTrue = super.onTouchEvent(event);  
  32.         Log.e(TAG, "onTouchEvent  isTrue = " + isTrue);  
  33.         return isTrue;  
  34.     }  
  35. }  


MyButtonWithOutEvent.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package org.sunday.main;  
  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 MyButtonWithOutEvent extends Button {  
  10.     private final static String TAG = "MyButtonWithOutEvent";  
  11.   
  12.     public MyButtonWithOutEvent(Context context) {  
  13.         super(context);  
  14.     }  
  15.   
  16.     public MyButtonWithOutEvent(Context context, AttributeSet attrs) {  
  17.         super(context, attrs);  
  18.     }  
  19.   
  20.     @Override  
  21.     public boolean dispatchTouchEvent(MotionEvent event) {  
  22.         Log.e(TAG, "dispatchTouchEvent()----------------"this.toString());  
  23. //      boolean isTrue = super.dispatchTouchEvent(event);  
  24. //      Log.e(TAG, "isTrue = " + isTrue);  
  25.         return false;  
  26.     }  
  27.       
  28.     @Override  
  29.     public boolean onTouchEvent(MotionEvent event) {  
  30.         Log.e(TAG, "onTouchEvent()----------------");  
  31.         boolean isTrue = super.onTouchEvent(event);  
  32.         Log.e(TAG, "onTouchEvent  isTrue = " + isTrue);  
  33.         return isTrue;  
  34.     }  
  35. }  


 点击例子一,后台打印的日志如下:

 

解释:例子一的布局中只有两个ViewGroup子类对象,当点击例子一区域,根ViewGroup首先分发touch事件,因为它有child,所以接着会将事件传递到它的孩子ViewGroup。孩子ViewGroup发现自己没有child了,所以它就得自己处理这个touch事件。所以会调用OnTouchEvent()方法来处理这个事件。处理完之后会返回一个true,一直返回给根ViewGroup。

 

点击例子二的绿色区域,后台打印日志如下:

解释:例子二和例子一差不多,只不过多了一个ViewGroup而已。

 

点击例子三得黄色区域,后台打印日志如下:

 解释:例子三相比于例子二只是将最上层的ViewGroup换成了View,原理一样。

 

点击例子四的黄色区域,打印日志如下:

解释:在这个程序中,对于MyLinearLayout和MyButton的dispachTouchEvent()和onTouchEvent()发放的逻辑并没有进行任何的修改。而对于MyButtonWithOutEvent,在dispatchTouchEvent()方法中,直接返回的false(即不进行事件的任何处理),那么事件传递到这里时,它将会把事件返回给调用它的父ViewGroup进行处理,所以这里我们看到的是MyLinearLayout调用了onTouchEvent()。

 

点击例子三得button和点击例子四的button效果图如下:

 例子三中是button响应了这个touch事件,而在例子四中则是LinearLayout响应了这个touch事件。

demo:点击打开链接

================================

其他参考链接

图解View的事件分发机制

http://www.tuicool.com/articles/ZVbUnme

Andriod 从源码的角度详解View,ViewGroup的Touch事件的分发机制

http://my.oschina.net/u/1538627/blog/217609?p={{totalPage}}

《Android深入透析》之Android事件分发机制

http://www.cnblogs.com/duoduohuakai/p/3996385.html

Android Touch事件传递机制解析

http://www.cnblogs.com/jqyp/archive/2012/04/25/2469758.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值