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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,763評論 6 539
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,238評論 3 428
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,823評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,604評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,339評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,713評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,712評論 3 445
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,893評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,448評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,201評論 3 357
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,397評論 1 372
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,944評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,631評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,033評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,321評論 1 293
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,128評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,347評論 2 377

推薦閱讀更多精彩內容