Android觸摸事件分發(fā)機(jī)制(2)之ViewGroup

Android觸摸事件分發(fā)機(jī)制(1)之View

上一篇文章我們分析了View的事件分發(fā)機(jī)制,今天我們分析下ViewGroup的時(shí)間分發(fā)機(jī)制。ViewGroup是View的子類,所以它肯定有繼承部分View的特性,當(dāng)然它也有自己的特性,二者具體有何不同呢?

例子

我們來(lái)舉一個(gè)栗子吧~

首先我們自定義Button和自定義LinearLayout,將Button放入在LinearLayout中,下面主要重寫部分方法,添加Log。

TestButton.java
public class TestButton extends Button {
    
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        Log.i("w", "TestButton dispatchTouchEvent-- action=" + event.getAction());
        return super.dispatchTouchEvent(event);
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.i("w", "TestButton onTouchEvent-- action=" + event.getAction());
        return super.onTouchEvent(event);
    }
}
TestLinearLayout.java
public class TestLinearLayout extends LinearLayout {

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.i("w", "TestLinearLayout onInterceptTouchEvent-- action=" + ev.getAction());
        return super.onInterceptTouchEvent(ev);
    }
    
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        Log.i("w", "TestLinearLayout dispatchTouchEvent-- action=" + event.getAction());
        return super.dispatchTouchEvent(event);
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.i("w", "TestLinearLayout onTouchEvent-- action=" + event.getAction());
        return super.onTouchEvent(event);
    }
}
main_activity.xml
<io.weimu.caoyang.TestLinearLayout      
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/mylayout">
    
    <io.weimu.caoyang.TestButton
        android:id="@+id/my_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click test"/>
        
</com.zzci.light.TestLinearLayout>
MainActivity.java
public class MainActivity.java extends Activity implements View.OnTouchListener, View.OnClickListener {
    private TestLinearLayout mLayout;
    private TestButton mButton;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.main);
    
        mLayout = (TestLinearLayout) this.findViewById(R.id.mylayout);
        mButton = (TestButton) this.findViewById(R.id.my_btn);
    
        mLayout.setOnTouchListener(this);
        mButton.setOnTouchListener(this);
    
        mLayout.setOnClickListener(this);
        mButton.setOnClickListener(this);
    }
    
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Log.i("w", v+" onTouch-- action="+event.getAction());
        return false;
    }
    
    @Override
    public void onClick(View v) {
        Log.i("w", v+" OnClick");
    }
}

讓我們看一下打印出來(lái)的Log(PS:0為DOWN,1為UP)

例子1:當(dāng)觸摸事件是在TestLinearLayout內(nèi),TestButton內(nèi)

消息
TestLinearLayout dispatchTouchEvent-- action=0
TestLinearLayout onInterceptTouchEvent-- action=0
TestButton dispatchTouchEvent-- action=0
TestButton onTouch-- action=0
TestButton onTouchEvent-- action=0
TestLinearLayout dispatchTouchEvent-- action=1
TestLinearLayout onInterceptTouchEvent-- action=1
TestButton dispatchTouchEvent-- action=1
TestButton onTouch-- action=1
TestButton onTouchEvent-- action=1
TestButton onClick

我們可以看出子View所得到的事件都是由父View派發(fā)所得的。整一個(gè)大概流程為:

  1. 執(zhí)行TestLinearLayout的DispatchTouchEvent
  2. 執(zhí)行TestLinearLayout的onIntercepTouchEvent
  3. 執(zhí)行TestButton的disPatchToucheEvent
  4. 接下去的分發(fā)流程與上一文章一致

例子2:當(dāng)觸摸事件在TestLinearLayout內(nèi),TestButton外

消息
TestLinearLayout dispatchTouchEvent-- action=0
TestLinearLayout onInterceptTouchEvent-- action=0
TestLinearLayout onTouch-- action=0
TestLinearLayout onTouchEvent-- action=0
TestLinearLayout dispatchTouchEvent-- action=1
TestLinearLayout onTouch-- action=1
TestLinearLayout onTouchEvent-- action=1
TestLinearLayout onClick

以上可以看到,沒(méi)有TestButton什么事情了~分發(fā)的流程基本與上面一致。有一處地方有點(diǎn)奇怪,就是當(dāng)action=1(ACTION_UP)時(shí),竟然沒(méi)有onInterceptTouchEvent。

ViewGroup和View既有些相似又很大的差異。View是所有視圖的最小單位,而ViewGroup一般內(nèi)部都包含著多個(gè)View。具體他們有啥區(qū)別呢?接下去我們來(lái)分析分析。

源碼解讀:

Step1 ViewGroup

從上面的Log,我們可以看出ViewGroup事件分發(fā)先觸發(fā)的是dispatchTouchEvent方法(此方法重寫了View的方法)。此方法代碼較多,代碼會(huì)盡量注釋,請(qǐng)耐心閱讀。

閱讀前的小準(zhǔn)備:

  • mFirstTouchTarget:判斷ViewGroup是否已經(jīng)找到可以傳遞事件的目標(biāo)組件
  • newTouchTarget:新的目標(biāo)組件
  • intercepted:標(biāo)記ViewGroup是否攔截Touch事件的傳遞
public boolean dispatchTouchEvent(MotionEvent ev) {
    ...
    boolean handled = false;
    if (onFilterTouchEventForSecurity(ev)) {
        final int action = ev.getAction();//獲取當(dāng)前的分發(fā)事件
        final int actionMasked = action & MotionEvent.ACTION_MASK;
        
        //【Part01】處理初始化按下操作
        if (actionMasked == MotionEvent.ACTION_DOWN) {
            //重置一切的點(diǎn)擊狀態(tài)
            cancelAndClearTouchTargets(ev);
            resetTouchState();
        }
    
        //【Part02】檢查是否要攔截
        final boolean intercepted;
        //只要事件為Down,或無(wú)傳遞的目標(biāo)組件
        if (actionMasked == MotionEvent.ACTION_DOWN
                || mFirstTouchTarget != null) {
            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
            //是否不允許攔截(此變量可設(shè)置,默認(rèn)為false)
            if (!disallowIntercept) {
                //☆重要的☆  
                intercepted = onInterceptTouchEvent(ev);
                ev.setAction(action); // restore action in case it was changed
            } else {
                intercepted = false;
            }
        } else {
            intercepted = true;
        }
        ...
        
        //【Part03】檢查取消操作,默認(rèn)為false
        final boolean canceled = resetCancelNextUpFlag(this)
                || actionMasked == MotionEvent.ACTION_CANCEL;
    
        //如果需要,更新目標(biāo)視圖列表
        final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
        TouchTarget newTouchTarget = null;//
        boolean alreadyDispatchedToNewTouchTarget = false;
        
        //【Part04】子View的掃描
        if (!canceled && !intercepted) {
                ...
                //獲取子View的數(shù)量
                final int childrenCount = mChildrenCount;
            //當(dāng)無(wú)傳遞的目標(biāo)組件,且子View數(shù)量不為0
                if (newTouchTarget == null && childrenCount != 0) {
                //獲取當(dāng)前子View的X,Y
                    final float x = ev.getX(actionIndex);
                    final float y = ev.getY(actionIndex);
                    
                    //從頭到尾掃描,找到一個(gè)可以接受事件分發(fā)的子View,
                    final ArrayList<View> preorderedList = buildOrderedChildList();
                    final boolean customOrder = preorderedList == null
                            && isChildrenDrawingOrderEnabled();
                    final View[] children = mChildren;
                    //for循環(huán)掃描
                    for (int i = childrenCount - 1; i >= 0; i--) {
                        final int childIndex = customOrder
                                ? getChildDrawingOrder(childrenCount, i) : i;
                        final View child = (preorderedList == null)
                                ? children[childIndex] : preorderedList.get(childIndex);
                        ...
                        
                        //判斷子View是否為VISIBLE,且判斷觸摸事件是否落在當(dāng)前子View
                        if (!canViewReceivePointerEvents(child)
                                || !isTransformedTouchPointInView(x, y, child, null)) {
                            ev.setTargetAccessibilityFocus(false);
                            continue;
                        }
                        //獲取新的傳遞控件
                        newTouchTarget = getTouchTarget(child);
                        if (newTouchTarget != null) {
                            newTouchTarget.pointerIdBits |= idBitsToAssign;
                            break;
                        }
    
                        resetCancelNextUpFlag(child);
                        
                         //☆重要的☆  【文章下面會(huì)分析】
                         //觸發(fā)子視圖的普通分發(fā)事件或者本身的普通分發(fā)事件
                        if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
                            ...
                            
                            //☆重要的☆  增加新的傳遞控件  【文章下面會(huì)分析】
                            //給mFirstTouchTarget賦值
                            newTouchTarget = addTouchTarget(child, idBitsToAssign);
                            alreadyDispatchedToNewTouchTarget = true;
                            break;
                        }
    
                        ev.setTargetAccessibilityFocus(false);
                    }
                    if (preorderedList != null) preorderedList.clear();
                }
                    
                    //如果沒(méi)找到子View可以傳遞事件,則將指針?lè)峙浣o最近添加的對(duì)象
                if (newTouchTarget == null && mFirstTouchTarget != null) {
                    newTouchTarget = mFirstTouchTarget;
                    while (newTouchTarget.next != null) {
                        newTouchTarget = newTouchTarget.next;
                    }
                    newTouchTarget.pointerIdBits |= idBitsToAssign;
                }
            }
        }
    
        //part05 分發(fā)事件給傳遞對(duì)象
        if (mFirstTouchTarget == null) {
            //因無(wú)傳遞對(duì)象,所以直接調(diào)用自身的普通傳遞事件
            handled = dispatchTransformedTouchEvent(ev, canceled, null,
                    TouchTarget.ALL_POINTER_IDS);
        } else {
            TouchTarget predecessor = null;
            TouchTarget target = mFirstTouchTarget;
            while (target != null) {
                final TouchTarget next = target.next;
                if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
                    handled = true;
                } else {
                    final boolean cancelChild = resetCancelNextUpFlag(target.child)
                            || intercepted;
                   //分發(fā)事件到指定的傳遞對(duì)象
                    if (dispatchTransformedTouchEvent(ev, cancelChild,
                            target.child, target.pointerIdBits)) {
                        handled = true;
                    }
                    if (cancelChild) {
                        if (predecessor == null) {
                            mFirstTouchTarget = next;
                        } else {
                            predecessor.next = next;
                        }
                        target.recycle();
                        target = next;
                        continue;
                    }
                }
                predecessor = target;
                target = next;
            }
        }
    
        //part06 刷新傳遞對(duì)象狀態(tài)
        if (canceled
                || actionMasked == MotionEvent.ACTION_UP
                || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
            resetTouchState();
        } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
            final int actionIndex = ev.getActionIndex();
            final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
            removePointersFromTouchTargets(idBitsToRemove);
        }
    }
    ...
    return handled;
}
Part01 處理初始化按下操作

當(dāng)我們每次按下(ACTION_DOWN)的時(shí)候會(huì)有初始化操作:cancelAndClearTouchTargets(ev)resetTouchState()里面有比較重要的操作:將mFirstTouchTarget初始化為null

Part02 檢查是否要攔截

if(actionMasked == MotionEvent.ACTION_DOWN|| mFirstTouchTarget != null)的判斷下,只要事件為ACTION_DOWN或者傳遞事件不為空,就可以進(jìn)入下一個(gè)執(zhí)行體,否則intercepted = true;在下一個(gè)執(zhí)行體中我們調(diào)用onInterceptTouchEvent并返回值給intercepted。

讓我們看一下onInterceptTouchEvent里寫了什么:

public boolean onInterceptTouchEvent(MotionEvent ev) {
    return false;
}

默認(rèn)返回返回false,也就是intercepted = false;

Part03 檢查取消操作,默認(rèn)為false

通過(guò)標(biāo)記和action檢查cancel,然后將結(jié)果賦值給局部boolean變量canceled。

Part04 子View的掃描

1.當(dāng)前觸摸事件的x,y,通過(guò)for循環(huán)掃描每個(gè)子View,判斷子View是否為VISIBLE和x,y是否落在當(dāng)前子View上,不是的話跳過(guò)此循環(huán),換下一個(gè)子View。

2.通過(guò)getTouchTarget(child);嘗試獲取newTouchTarget

//為指定的子View獲取觸摸對(duì)象,如果沒(méi)發(fā)現(xiàn)返回空
private TouchTarget getTouchTarget(@NonNull View child) {
    for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
    
        //判斷當(dāng)前target所對(duì)應(yīng)的view是否與傳入的View相同
        if (target.child == child) {
            return target;
        }
    }
    return null;
}

3.接著調(diào)用方法dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)將觸摸事件傳遞給特定的子View!!!此方法重點(diǎn)在于第三個(gè)參數(shù),如果傳子View,內(nèi)部會(huì)調(diào)用子View的dispatchTouchEvent進(jìn)行子View的普通觸摸事件分發(fā)并返回參數(shù),而傳入null時(shí),會(huì)調(diào)用父類的super.dispatchTouchEvent進(jìn)行父View的普通觸摸事件分發(fā)并返回參數(shù)。

在這種情況下,如果dispatchTransformedTouchEvent為false,即子View沒(méi)有消費(fèi)。為ture,表明子View消費(fèi)了。

4.當(dāng)子View消費(fèi)事件時(shí),通過(guò)addTouchTarget給newTouchTarget賦值,給alreadyDispatchedToNewTouchTarget賦值為true。

//給mFirstTouchTarget賦值!!!
private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
    final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
    target.next = mFirstTouchTarget;
    mFirstTouchTarget = target;
    return target;
}

到這里我們可以稍微總結(jié)一下:dispatchTransformedTouchEvent的返回值

return description mFirstTouchTarget
ture 事件被消費(fèi)(子View或自身) 賦值
false 事件未消費(fèi)(子View或自身) null

5.接下來(lái)if (newTouchTarget == null && mFirstTouchTarget != null) 該if表示經(jīng)過(guò)前面的for循環(huán)沒(méi)有找到子View接收Touch事件并且之前的mFirstTouchTarget不為空則為真,然后newTouchTarget指向了最初的TouchTarget。

Part05 分發(fā)事件給傳遞對(duì)象

經(jīng)過(guò)上面的流程后,接著if (mFirstTouchTarget == null)判斷

mFirstTouchTarget為空時(shí),表明觸摸事件未被消費(fèi),即觸摸事件被攔截或找不到目標(biāo)子View。此時(shí)調(diào)用dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS)
內(nèi)部在調(diào)用super.dispatchTouchEvent進(jìn)行父View的普通觸摸事件分發(fā)

mFirstTouchTarget不為null,依然是遞歸調(diào)用dispatchTransformedTouchEvent()方法來(lái)實(shí)現(xiàn)的處理。

part06 刷新傳遞對(duì)象狀態(tài)

當(dāng)觸摸事件為ACTION_UP或ACTION_HOVER_MOVE時(shí)刷新傳遞對(duì)象的狀態(tài),mFirstTouchTarget = null;將mFirstTouchTarget置空等操作

Step2 ViewGroup

以上dispatchTouchEvent分析完畢,此外我們這里在分析下上面經(jīng)常用到的一個(gè)方法dispatchTransformedTouchEvent()

private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
        View child, int desiredPointerIdBits) {
    //由于重復(fù)代碼較多,直接提取精簡(jiǎn)代碼
    final boolean handled;
     if (child == null) {
            handled = super.dispatchTouchEvent(event);//父類的普通事件分發(fā)
        } else {
            handled = child.dispatchTouchEvent(event);//子類的普通事件分發(fā)
     }
     return handled;
 }

這個(gè)方法是ViewGroup獨(dú)特于View的一個(gè)方法。我們上面的分析也大概講了一下這個(gè)方法:第三個(gè)參數(shù)有無(wú)對(duì)象,直接影到了內(nèi)部的調(diào)用【child -> view.dispatchTouchEvent】【null -> super.dispatchTouchEvent】

總結(jié) Summary

  1. Android事件派發(fā)是先傳遞到最頂級(jí)的ViewGroup,再由ViewGroup遞歸傳遞到View的。
  2. 在ViewGroup中可以通過(guò)onInterceptTouchEvent方法對(duì)事件傳遞進(jìn)行攔截,onInterceptTouchEvent方法返回true代表攔截不向子View傳遞,返回false代表不對(duì)事件進(jìn)行攔截。默認(rèn)返回false。
  3. 子View中如果將傳遞的事件消費(fèi)掉,ViewGroup中將無(wú)法接收到任何事件。

Andorid觸摸事件分發(fā)機(jī)制(3)之Activity


PS:本文整理自以下文章,若有發(fā)現(xiàn)問(wèn)題請(qǐng)致郵 caoyanglee92@gmail.com
工匠若水 Android觸摸屏事件派發(fā)機(jī)制詳解與源碼分析二(ViewGroup篇)
Hongyang Android ViewGroup事件分發(fā)機(jī)制

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容