1. 程式人生 > >Android事件傳遞機制詳解(巢狀自定義View示例)

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.點選螢幕,事件的傳遞從ActivitydispatchTouchEvent()方法開始。

2.在時間上,同一層級的分發順序為dispatchTouchEvent(分發) --- onInterceptTouchEvent(如果攔截) --- onTouchEvent(消費)

後兩個方法的預設返回值都是false,ViewGroup的

dispatchTouchEvent預設返回true,View的dispatchTouchEvent預設返回false,程式碼在下文中。



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

     a) 向下分發過程,該過程主要呼叫dispatchTouchEvent,該方法內會呼叫onInterceptTouchEvent,如果返回true,則證明事件在本層攔截,事件傳遞給本層的onTouchListeneronTouchEvent來處理。如果不攔截,則嘗試找到點選的子View,如果沒找到,則繼續分發事件。當分發到View(非ViewGroup)的dispatchTouchEvent

,它會將事件直接傳遞給onTouchListeneronTouchEvent。(上面已經說,非容器類View沒有onInterceptTouchEvent方法。)

貼上別人總結的虛擬碼:

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事件的關係  
     }  
}  

b) 向上返回過程,主要依靠onTouchEvent方法。如果其返回值是false,則說明沒有處理事件,這個事件還得由“上級領導”出馬擺平,於是事件被回傳到上一層的onTouchEvent。重複此過程,直到事件被“處理消費”,或回傳到最終的Activity。說到這裡,A這就是為什麼ctivity的onTouchEvent總能接收到事件的原因,當然前提是我們沒有做什麼特殊處理,改變某個子View的onTouchEvent返回值。

值得注意的是

     在開發中,最常用的3個動作事件就是:ACTION_DOWNACTION_MOVEACTION_UP

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

     SDK中有提及,在ViewGrouponInterceptTouchEvent方法中,如果在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了(注意標紅字型)。下面這個例子可以證明:

   @Override
    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);
    }

結果截圖


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

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);
    }
}

2. 新建一個子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);
    }
}



3. 在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.執行結果


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

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


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


事件D並沒有觸發。

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