Android事件傳遞機制詳解(嵌套自定義View示例)

一、概述

自定義View如果嵌套了自定義View,可能簡單寫一個onTouchEvent處理事件已經不能解決你的需要。簡單舉個例子:

你自定義了一個容器View,簡稱為父View,在這里監聽點擊事件,做事情A,監聽滑動做事情B

然后你又自定了一個View,放入該容器父View當中,也監聽點擊事件,當點擊的時候做事件C,滑動時做事情D。

上面的事件A、C不是互斥的,意味著點擊發生時,在子View中做一部分處理工作,然后父View中也做一部分處理工作。

事情B和D是互斥的,即父View發生滑動,則只做事情B

遇到這種情況,不理解清楚Android的事件傳遞機制是不行的。

二、理解Android的事件傳遞機制

一般的View都有dispatchTouchEvent,onTouchEvent方法,這個是從View中繼承的,而具備容器功能的View如LinearLayout,額外多了onInterceptTouchEvent方法,這個是從ViewGroup父類中繼承到的。

事件傳遞開始的順序,一般如下:

1.點擊屏幕,事件的傳遞從Activity的dispatchTouchEvent()方法開始。

2.在時間上,同一層級的分發順序為

dispatchTouchEvent(分發) --- 
onInterceptTouchEvent(如果攔截) --- 
onTouchEvent(消費)

后兩個方法的默認返回值都是false,ViewGroup的dispatchTouchEvent默認返回true,View的dispatchTouchEvent默認返回false,代碼在下文中。


image

3.Android事件分發機制一般分為兩個過程,先從上往下傳遞,再從下往上傳遞。

  • 向下分發過程:該過程主要調用dispatchTouchEvent,該方法內會調用onInterceptTouchEvent,如果返回true,則證明事件在本層攔截,事件傳遞給本層的onTouchListener,onTouchEvent來處理。如果不攔截,則嘗試找到點擊的子View,如果沒找到,則繼續分發事件。當分發到View(非ViewGroup)的dispatchTouchEvent,它會將事件直接傳遞給onTouchListener,onTouchEvent。(上面已經說,非容器類View沒有onInterceptTouchEvent方法。)

貼上別人總結的偽代碼:

[java] view plain copy 在CODE上查看代碼片派生到我的代碼片
public boolean dispatchTouchEvent(MotionEvent ev) {    
     調用onInterceptTouchEvent檢查是否攔截事件    
     if(沒有攔截){    
         在ViewGroup中遍歷查找目前是點擊了哪個子視圖    
         if(找到了){    
             調用該子視圖的dispatchTouchEvent,遞歸下去    
         }else{    
             沒找到,則將事件傳給onTouchListener,沒有Listener則傳給onTouchEvent()    
             如果再listener或者onTouchEvent()中down事件返回了true,代表事件被消費,后續的move和up都被Listener或者onTouchEvent()處理,    
             如果down事件返回false,則后續的move,up事件將不會到這一層的Viewgroup,而直接在上一層視圖被消費。    
         }     
     }else{    
         事件被攔截了,原本被點擊的子視圖將接收到一個ACTION_CANCEL事件,而down事件傳給onTouchListener,沒有Listener則傳給onTouchEvent(),依然遵從上面的down和move,up事件的關系    
     }    
}
  • 向上返回過程:主要依靠onTouchEvent方法。如果其返回值是false,則說明沒有處理事件,這個事件還得由“上級領導”出馬擺平,于是事件被回傳到上一層的onTouchEvent。重復此過程,直到事件被“處理消費”,或回傳到最終的Activity。說到這里,A這就是為什么ctivity的onTouchEvent總能接收到事件的原因,當然前提是我們沒有做什么特殊處理,改變某個子View的onTouchEvent返回值。

注意點

  • 在開發中,最常用的3個動作事件就是:ACTION_DOWN、ACTION_MOVE、ACTION_UP。

  • 這三個事件標識出了最基本的用戶觸摸屏幕的操作,含義也很清楚。雖然大家天天都在用它們,但是有一點請留意,ACTION_DOWN事件作為起始事件,它的重要性是要超過ACTION_MOVE和ACTION_UP的,如果發生了ACTION_MOVE或者ACTION_UP,那么一定曾經發生了ACTION_DOWN。(比如,用戶在屏幕上滑動一下,最先傳遞過來的事件肯定是ACTION_DOWN)

  • SDK中有提及,在ViewGroup的onInterceptTouchEvent方法中,如果在ACTION_DOWN事件中返回了true,那么后續的事件將直接發給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.  
    *  
    * <p>Using this function takes some care, as it has a fairly complicated  
    * interaction with {@link View#onTouchEvent(MotionEvent)  
    * 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:  
    *  
    * <ol>  
    * <li> You will receive the down event here.  
    * <li> 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.  
    * <li> 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().  
    * <li> 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 {@link MotionEvent#ACTION_CANCEL}, and all further  
    * events will be delivered to your onTouchEvent() method and no longer  
    * appear here.  
    * </ol>  
    *  
    * @param ev The motion event being dispatched down the hierarchy.  
    * @return Return true to steal motion events from the children and have  
    * them dispatched to this ViewGroup through onTouchEvent().  
    * The current target will receive an ACTION_CANCEL event, and no further  
    * messages will be delivered here.  
    */    
   public boolean onInterceptTouchEvent(MotionEvent ev) {    
       return false;    
   }
  • 還有一點,如果ACTION_DOWN事件中返回了false,那么在==這一次動作中==后續的“更先進”的事件就不會再傳遞到當前View了(注意注釋)。下面這個例子可以證明:
public boolean onTouchEvent(MotionEvent event) {  
     
     if(event.getAction()==MotionEvent.ACTION_DOWN) {  
         Log.i("test", "ACTION_DOWN發生");  
         return false;  
     }  
     //判斷是向下滑動  
     if(event.getAction()==MotionEvent.ACTION_MOVE) {  
         Log.i("test", "ACTION_MOVE發生");  //這條語句是不會執行的  
     }  
      
     return super.onTouchEvent(event);  
 }

結果截圖


image

三、實現第一點中提出的效果。

  1. 新建一個父類,代碼如下
package com.example.administrator.myapplication;  
  
import android.content.Context;  
import android.util.AttributeSet;  
import android.util.Log;  
import android.view.MotionEvent;  
import android.widget.LinearLayout;  
  
/** 
 * Created by wangqinwei on 2016/10/20. 
 */  
  
public class MyFatherContainer extends LinearLayout {  
  
    public MyFatherContainer(Context context) {  
        super(context);  
    }  
  
    public MyFatherContainer(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        setBackgroundColor(getResources().getColor(R.color.colorPrimary));  
    }  
  
    public MyFatherContainer(Context context, AttributeSet attrs, int defStyleAttr) {  
        super(context, attrs, defStyleAttr);  
    }  
  
    @Override  
    public boolean dispatchTouchEvent(MotionEvent event) {  
        Log.i("WQW", "父View的dispatchTouchEvent被調用,默認返回:" + super.dispatchTouchEvent(event));  
  
        return super.dispatchTouchEvent(event);  
    }  
  
    @Override  
    public boolean onInterceptTouchEvent(MotionEvent ev) {  
        Log.i("WQW", "父View的onInterceptTouchEvent被調用,默認返回:" + super.onInterceptTouchEvent(ev));  
  
        if (ev.getAction() == MotionEvent.ACTION_MOVE) {  
            Log.i("test", "父View攔截滑動");  
            return true;  
        }  
  
        return super.onInterceptTouchEvent(ev);  
    }  
  
    @Override  
    public boolean onTouchEvent(MotionEvent event) {  
        Log.i("WQW", "父View的onTouchEvent被調用,默認返回:" + super.onTouchEvent(event));  
  
        if (event.getAction() == MotionEvent.ACTION_DOWN) {  
            Log.i("test", "父View發生點擊,做事情A");  
            return true;   //這里一定要返回true,否則后續收不到滑動事件了  
        }  
  
        if (event.getAction() == MotionEvent.ACTION_MOVE) {  
            Log.i("test", "父View發生滑動,做事情B");  
        }  
        return super.onTouchEvent(event);  
    }  
}
  1. 新建一個子View
package com.example.administrator.myapplication;  
  
import android.content.Context;  
import android.util.AttributeSet;  
import android.util.Log;  
import android.view.MotionEvent;  
import android.view.View;  
  
public class MyChildView extends View {  
  
    public MyChildView(Context context) {  
        super(context);  
    }  
  
    public MyChildView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        setBackgroundColor(getResources().getColor(R.color.colorAccent));  
    }  
  
    public MyChildView(Context context, AttributeSet attrs, int defStyleAttr) {  
        super(context, attrs, defStyleAttr);  
    }  
  
    @Override  
    public boolean dispatchTouchEvent(MotionEvent event) {  
        Log.i("WQW", "子View的dispatchTouchEvent被調用,默認返回:" + super.dispatchTouchEvent(event));  
  
        return super.dispatchTouchEvent(event);  
    }  
  
    @Override  
    public boolean onTouchEvent(MotionEvent event) {  
        Log.i("WQW", "子View的onTouchEvent被調用,默認返回:" + super.onTouchEvent(event));  
  
        if (event.getAction() == MotionEvent.ACTION_DOWN) {  
            Log.i("test", "子View發生點擊,做事情C");  
            return false;  //同時返回false,讓事件返回給上層  
        }  
  
        if (event.getAction() == MotionEvent.ACTION_MOVE) { //這里其實父類攔截與否沒有意義,因為ACTION_DOWN返回了false  
            Log.i("test", "子View發生滑動,做事情D");  
        }  
  
        return super.onTouchEvent(event);  
    }  
}
  1. 在Activity的布局文件中使用父View和子View
<?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:id="@+id/activity_main"  
    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.example.administrator.myapplication.MainActivity"  
    >  
  
    <com.example.administrator.myapplication.MyFatherContainer  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:gravity="center"  
        >  
  
        <com.example.administrator.myapplication.MyChildView  
            android:layout_width="300dp"  
            android:layout_height="400dp"  
            />  
  
    </com.example.administrator.myapplication.MyFatherContainer>  
  
  
</RelativeLayout>

4.運行結果

image

其中紅色的部分是子View,藍色部分是父View。

在子View上點擊,結果如下:


image

在子View上滑動,結果如下:


image

事件D并沒有觸發。

如果覺得我的文章幫到了你,請留個言唄~

參考的優秀博客: http://blog.csdn.net/chziroy/article/details/44401615

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容