Android View事件分發機制
作為程式猿,最不想 看的但是也不得不去看的就是原始碼!所謂知其然也要知其所以然,神祕的大佬曾經說過進階的方法就是READ THE FUCKING CODE!
認識MotionEvent
負責集中處理所有型別裝置的輸入事件.我們對螢幕的點選,滑動,擡起等一系的動作都是由一個一個MotionEvent物件組成的。
主要事件型別
- ACTION_DOWN 手機初次觸控到螢幕事件
- ACTION_MOVE 手機在螢幕上滑動時觸發,會回撥多次
- ACTION_UP 手指離開螢幕時觸發
主要方法
- getAction() 獲取事件型別
- getX() 獲取觸控點在當前View的X軸座標
- getY() 獲得觸控點在當前 View 的 Y 軸座標
- getRawX() 獲得觸控點在整個螢幕的 X 軸座標
- getRawY() 獲得觸控點在整個螢幕的 Y 軸座標
上面這些是基本操作.下面我們來看一個小東西:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView (R.layout.activity_main)
btn_test.setOnTouchListener { v, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
Log.e("xfhy", "ACTION_DOWN")
}
MotionEvent.ACTION_MOVE -> {
Log. e("xfhy", "ACTION_MOVE")
}
MotionEvent.ACTION_UP -> {
Log.e("xfhy", "ACTION_UP")
}
else -> {
}
}
//返回false
false
}
btn_test.setOnClickListener {
Log.e("xfhy", "點選事件")
}
}
}
最後執行結果是
2018-10-15 17:51:19.766 9257-9257/com.xfhy.clickdemo E/xfhy: ACTION_DOWN
2018-10-15 17:51:19.785 9257-9257/com.xfhy.clickdemo E/xfhy: ACTION_MOVE
2018-10-15 17:51:19.844 9257-9257/com.xfhy.clickdemo E/xfhy: ACTION_MOVE
2018-10-15 17:51:19.844 9257-9257/com.xfhy.clickdemo E/xfhy: ACTION_UP
2018-10-15 17:51:19.848 9257-9257/com.xfhy.clickdemo E/xfhy: 點選事件
onClick()是在ACTION_UP之後才呼叫的.
至於為什麼,稍後會給出解釋(原始碼就是這樣寫的).
MotionEvent事件分發
當一個MotionEvent產生後,需要分發給一個具體的View,去消化處理.我們需要去了解這個分發的過程.
下面有幾個重要的方法,簡單介紹一下:
- public boolean dispatchTouchEvent(MotionEvent event) 事件的分發.對於一個根ViewGroup來說,發生點選事件首先呼叫dispatchTouchEvent()
- public boolean onInterceptTouchEvent(MotionEvent ev)
事件攔截.如果這個ViewGroup的onIterceptTouchEvent返回true就表示它要攔截當前事件,接著這個ViewGroup的onTouchEvent就會被呼叫.如果onIterceptTouchEvent返回false,那麼就會繼續向下呼叫子View的dispatchTouchEvent方法.一旦一個元素攔截了某事件,那麼一個事件序列裡面後續的Move,Down事件都會交給它處理.並且它的onInterceptTouchEvent不會再呼叫. - public boolean onTouchEvent(MotionEvent ev) 事件處理.View的預設實現會在onTouchEvent裡面把touch事件解析成Click之類的事件.View的onTouchEvent預設都會消耗事件,除非它的clickable和longClickable都是false(不可點選),但是enable屬性不會影響.
- 點選事件傳遞順序 Activity -> Window -> View
下面是View事件分發流程圖:
現在,我們隊View的事件分發有了一個大致的瞭解.
上面的三個方法可以用以下虛擬碼來表示其關係:
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean consume = false;//事件是否被消費
if (onInterceptTouchEvent(ev)){//呼叫onInterceptTouchEvent判斷是否攔截事件
consume = onTouchEvent(ev);//如果攔截則呼叫自身的onTouchEvent方法
}else{
consume = child.dispatchTouchEvent(ev);//不攔截呼叫子View的dispatchTouchEvent方法
}
return consume;//返回值表示事件是否被消費,true事件終止,false呼叫父View的onTouchEvent方法
}
通過上面的介紹,差不多簡單瞭解了事件的傳遞機制.下面我們來看看原始碼:
原始碼分析
事件從最先到達Activity,我們來看一下Activity的dispatchTouchEvent()
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//一個空方法,一般用於開發者想監聽某個點選事件的開始
onUserInteraction();
}
//交給Window去分發
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
//如果沒人處理這個事件,那麼當前Activity去處理
return onTouchEvent(ev);
}
上面是getWindow().superDispatchTouchEvent(ev).交給Window去分發事件.
然後Window只有一個實現類PhoneWindow,其實最後就是呼叫的PhoneWindow中的superDispatchTouchEvent(ev).
### PhoneWindow部分程式碼
private DecorView mDecor;
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
咦,看到沒有,其實是通過頂級View–DecorView去分發事件,嗯,很合乎常理.從上往下分配任務.
下面是DecorView的程式碼
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
再跟進super.dispatchTouchEvent(event);,就來到了ViewGroup(顯然,DecorView是ViewGroup).
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handled = false;
// 判斷當前View是否沒被遮蓋住 如果是遮蓋住了,則不進行事件分發
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
//處理初次的按下事件
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous
// gesture
// due to an app switch, ANR, or some other state change.
//在開始新的觸控手勢時丟棄所有先前的狀態。
cancelAndClearTouchTargets(ev);
//重置所有觸控狀態以準備新週期。
resetTouchState();
}
//檢測攔截
final boolean intercepted;
//事件是按下
if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {
//判斷是否禁止攔截 當子View呼叫requestDisallowInterceptTouchEvent(true)之後,這裡的disallowIntercept就是true->禁止攔截 因為子類想接收這個事件並處理自己的邏輯
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) { //子類沒有禁止攔截
//是否需要攔截事件 子類可以實現onInterceptTouchEvent()去很輕鬆的實現事件攔截
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
//檢查是否已經被取消了
final boolean canceled = resetCancelNextUpFlag(this) || actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
//如果沒被取消 && 沒有被攔截
if (!canceled && !intercepted) {
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
final int actionIndex = ev.getActionIndex(); // always 0 for down
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) : TouchTarget.ALL_POINTER_IDS;
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
// Find a child that can receive the event.
// Scan children from front to back.
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null && isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(preorderedList, children, childIndex);
// If there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
// a.如果View不可見並且沒有播放動畫
// b.點選事件的座標落在View的範圍內
// 滿足a或者b則不分發事件給這個view
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
//子View已經接收觸控事件在自己的範圍內,則直接跳出迴圈,將事件給它自己處理.
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
//這裡實際上是去呼叫child的dispatchTouchEvent(event);->子類去分發事件.
//ps: ViewGroup才能分發事件,View不能分發.
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
//子類想自己接收該事件(在自己的範圍內)
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
// childIndex points into presorted list, find original index
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
//將child賦值給mFirstTouchTarget
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
//如果某個child處理了事件,那麼就不用繼續迴圈了,直接跳出迴圈.
break;
}
// The accessibility focus didn't handle the event, so clear
// the flag and do a normal dispatch to all children.
ev.setTargetAccessibilityFocus(false);
}
if (preorderedList != null)
preorderedList.clear();
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// Dispatch to touch targets.
if (mFirstTouchTarget == null) {
//沒有child接收該事件,則呼叫super.dispatchTouchEvent(event); 將該事件交給View去處理
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null, TouchTarget.ALL_POINTER_IDS);
}
return handled;
}
//在ViewGroup中,比View多了一個方法—onInterceptTouchEvent()方法,這個是幹嘛用的呢,是用來進行事件攔截的,如果被攔截,事件就不會往下傳遞了,不攔截則繼續。
//子類可以去實現這個方法,然後就可以輕鬆的攔截事件啦.
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.isFromSource(InputDevice.SOURCE_MOUSE)
&& ev.getAction() == MotionEvent.ACTION_DOWN
&& ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)
&& isOnScrollbarThumb(ev.getX(), ev.getY())) {
return true;
}
return false;
}
/*
是否能收到事件: 如果可見或者沒有播放動畫
*/
private static boolean canViewReceivePointerEvents(@NonNull View child) {
return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
|| child.getAnimation() != null;
}
上面是ViewGroup的分發事件原始碼,只抽取了原始碼的部分,關鍵部分加入了註釋.
結論
ViewGroup會遍歷所有子View去尋找能夠處理點選事件的子View(可見,沒有播放動畫,點選事件座標落在子View內部)最終呼叫子View的dispatchTouchEvent方法處理事件
當子View處理了事件則mFirstTouchTarget 被賦值,並終止子View的遍歷。
如果ViewGroup並沒有子View或者子View處理了事件,但是子View的dispatchTouchEvent返回了false(一般是子View的onTouchEvent方法返回false)那麼ViewGroup會去處理這個事件(本質呼叫View的dispatchTouchEvent去處理)
下面來看一下View的dispatchTouchEvent()
public boolean dispatchTouchEvent(MotionEvent event) {
...
boolean result = false;
//如果視窗沒有被遮蓋
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
//監聽事件
ListenerInfo li = mListenerInfo;
//這裡的li.mOnTouchListener.onTouch(this, event)是有返回值的,如果是返回了true,那麼result就是true了. 相當於處理了觸控事件
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
//result為false時呼叫自己的onTouchEvent()去處理該事件.
if (!result && onTouchEvent(event)) {
result = true;
}
}
...
return result;
}
從上面的程式碼中可以看出,如果設定了OnTouchListener並且onTouch方法返回了true,那麼onTouchEvent不會被呼叫。
我們來看看onTouchEvent()方法
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
//CLICKABLE和LONG_CLICKABLE任何一個都可以消費該事件
//TextView預設是clickable是false,Button預設是true
//設定setOnClickListener()時會將clickable置為true
//設定setOnLongClickListener()時會將longClickable置為true
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
//即使View被設定成了不可用(setEnable(false)->DISABLED),但它還是可以消費點選事件
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return clickable;
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
switch (action) {
case MotionEvent.ACTION_UP:
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
if ((viewFlags & TOOLTIP) == TOOLTIP) {
handleTooltipUp();
}
if (!clickable) {
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
}
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
// take focus if we don't have it already and we should in
// touch mode.
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (prepressed) {
// The button is being released before we actually
// showed it as pressed. Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
setPressed(true, x, y);
}
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
// Only perform take click actions if we were in the pressed state
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
//在ACTION_UP 方法發生時,會觸發performClick()方法.
performClick();
}