Android點(diǎn)擊事件派發(fā)機(jī)制源碼分析
概述
一直想寫(xiě)篇關(guān)于Android事件派發(fā)機(jī)制的文章,卻一直沒(méi)寫(xiě),這兩天剛好是周末,有時(shí)間了,想想寫(xiě)一篇吧,不然總是只停留在會(huì)用的層次上但是無(wú)法了解其內(nèi)部機(jī)制。我用的是4.4源碼,打開(kāi)看看,挺復(fù)雜的,尤其是事件是怎么從Activity派發(fā)出來(lái)的,太費(fèi)解了。了解Windows消息機(jī)制的人會(huì)發(fā)現(xiàn),覺(jué)得Android的事件派發(fā)機(jī)制和Windows的消息派發(fā)機(jī)制挺像的,其實(shí)這是一種典型的消息“冒泡”機(jī)制,很多平臺(tái)采用這個(gè)機(jī)制,消息最先到達(dá)最底層View,然后它先進(jìn)行判斷是不是它所需要的,否則就將消息傳遞給它的子View,這樣一來(lái),消息就從水底的氣泡一樣向上浮了一點(diǎn)距離,以此類推,氣泡達(dá)到頂部和空氣接觸,破了(消息被處理了),當(dāng)然也有氣泡浮出到頂層了,還沒(méi)破(消息無(wú)人處理),這個(gè)消息將由系統(tǒng)來(lái)處理,對(duì)于Android來(lái)說(shuō),會(huì)由Activity來(lái)處理。
Android點(diǎn)擊事件的派發(fā)機(jī)制
1. 從Activity傳遞到底層View
點(diǎn)擊事件用MotionEvent來(lái)表示,當(dāng)一個(gè)點(diǎn)擊操作發(fā)生時(shí),事件最先傳遞給當(dāng)前Activity,由Activity的dispatchTouchEvent來(lái)進(jìn)行事件派發(fā),具體的工作是由Activity內(nèi)部的Window來(lái)完成的,Window會(huì)將事件傳遞給decor view,decor view一般就是當(dāng)前界面的底層容器(即setContentView所設(shè)置的View的父容器),通過(guò)Activity.getWindow.getDecorView()可以獲得。另外,看下面代碼的的時(shí)候,主要看我注釋的地方,代碼很多很復(fù)雜,我無(wú)法一一說(shuō)明,但是我注釋的地方都是關(guān)鍵點(diǎn),是博主仔細(xì)讀代碼總結(jié)出來(lái)的。
源碼解讀:
事件是由哪里傳遞給Activity的,這個(gè)我還不清楚,但是不要緊,我們從activity開(kāi)始分析,已經(jīng)足夠我們了解它的內(nèi)部實(shí)現(xiàn)了。
Code:Activity#dispatchTouchEvent
/**
* Called to process touch screen events. You can override this to
* intercept all touch screen events before they are dispatched to the
* window. Be sure to call this implementation for touch screen events
* that should be handled normally.
*
* @param ev The touch screen event.
*
* @return boolean Return true if this event was consumed.
*/
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//這個(gè)函數(shù)其實(shí)是個(gè)空函數(shù),啥也沒(méi)干,如果你沒(méi)重寫(xiě)的話,不用關(guān)心
onUserInteraction();
}
//這里事件開(kāi)始交給Activity所附屬的Window進(jìn)行派發(fā),如果返回true,整個(gè)事件循環(huán)就結(jié)束了
//返回false意味著事件沒(méi)人處理,所有人的onTouchEvent都返回了false,那么Activity就要來(lái)做最后的收?qǐng)觥?
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
//這里,Activity來(lái)收?qǐng)隽?,Activity的onTouchEvent被調(diào)用
return onTouchEvent(ev);
}
Window是如何將事件傳遞給ViewGroup的
Code:Window#superDispatchTouchEvent
/** * Used by custom windows, such as Dialog, to pass the touch screen event * further down the view hierarchy. Application developers should * not need to implement or call this. * */ public abstract boolean superDispatchTouchEvent(MotionEvent event);
這竟然是一個(gè)抽象函數(shù),還注明了應(yīng)用開(kāi)發(fā)者不要實(shí)現(xiàn)它或者調(diào)用它,這是什么情況?再看看如下類的說(shuō)明,大意是說(shuō):這個(gè)類可以控制頂級(jí)View的外觀和行為策略,而且還說(shuō)這個(gè)類的唯一一個(gè)實(shí)現(xiàn)位于android.policy.PhoneWindow,當(dāng)你要實(shí)例化這個(gè)Window類的時(shí)候,你并不知道它的細(xì)節(jié),因?yàn)檫@個(gè)類會(huì)被重構(gòu),只有一個(gè)工廠方法可以使用。好吧,還是很模糊啊,不太懂,不過(guò)我們可以看一下android.policy.PhoneWindow這個(gè)類,盡管實(shí)例化的時(shí)候此類會(huì)被重構(gòu),但是重構(gòu)而已,功能是類似的。
Abstract base class for a top-level window look and behavior policy. An instance of this class should be used as the top-level view added to the window manager. It provides standard UI policies such as a background, title area, default key processing, etc.The only existing implementation of this abstract class is android.policy.PhoneWindow, which you should instantiate when needing a Window. Eventually that class will be refactored and a factory method added for creating Window instances without knowing about a particular implementation.
Code:PhoneWindow#superDispatchTouchEvent
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}這個(gè)邏輯很清晰了,PhoneWindow將事件傳遞給DecorView了,這個(gè)DecorView是啥呢,請(qǐng)看下面
private final class DecorView extends FrameLayout implements RootViewSurfaceTaker
// This is the top-level view of the window, containing the window decor.
private DecorView mDecor;
@Override
public final View getDecorView() {
if (mDecor == null) {
installDecor();
}
return mDecor;
}
順便說(shuō)一下,平時(shí)Window用的最多的就是((ViewGroup)getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0)即通過(guò)Activity來(lái)得到內(nèi)部的View。這個(gè)mDecor顯然就是getWindow().getDecorView()返回的View,而我們通過(guò)setContentView設(shè)置的View是它的一個(gè)子View。目前事件傳遞到了DecorView 這里,由于DecorView 繼承自FrameLayout且是我們的父View,所以最終事件會(huì)傳遞給我們的View,原因先不管了,換句話來(lái)說(shuō),事件肯定會(huì)傳遞到我們的View,不然我們的應(yīng)用如何響應(yīng)點(diǎn)擊事件呢。不過(guò)這不是我們的重點(diǎn),重點(diǎn)是事件到了我們的View以后應(yīng)該如何傳遞,這是對(duì)我們更有用的。從這里開(kāi)始,事件已經(jīng)傳遞到我們的頂級(jí)View了,注意:頂級(jí)View實(shí)際上是最底層View,也叫根View。
2.底層View對(duì)事件的分發(fā)過(guò)程
點(diǎn)擊事件到底層View(一般是一個(gè)ViewGroup)以后,會(huì)調(diào)用ViewGroup的dispatchTouchEvent方法,然后的邏輯是這樣的:如果底層ViewGroup攔截事件即onInterceptTouchEvent返回true,則事件由ViewGroup處理,這個(gè)時(shí)候,如果ViewGroup的mOnTouchListener被設(shè)置,則會(huì)onTouch會(huì)被調(diào)用,否則,onTouchEvent會(huì)被調(diào)用,也就是說(shuō),如果都提供的話,onTouch會(huì)屏蔽掉onTouchEvent。在onTouchEvent中,如果設(shè)置了mOnClickListener,則onClick會(huì)被調(diào)用。如果頂層ViewGroup不攔截事件,則事件會(huì)傳遞給它的在點(diǎn)擊事件鏈上的子View,這個(gè)時(shí)候,子View的dispatchTouchEvent會(huì)被調(diào)用,到此為止,事件已經(jīng)從最底層View傳遞給了上一層View,接下來(lái)的行為和其底層View一致,如此循環(huán),完成整個(gè)事件派發(fā)。另外要說(shuō)明的是,ViewGroup默認(rèn)是不攔截點(diǎn)擊事件的,其onInterceptTouchEvent返回false。
源碼解讀:
Code:ViewGroup#dispatchTouchEvent
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
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();
}
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
//這里判斷是否攔截點(diǎn)擊事件,如果攔截,則intercepted=true
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;
}
// Check for cancelation.
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;
//這里面一大堆是派發(fā)事件到子View,如果intercepted是true,則直接跳過(guò)
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;
// Clean up earlier touch targets for this pointer id in case they
// have become out of sync.
removePointersFromTouchTargets(idBitsToAssign);
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 View[] children = mChildren;
final boolean customOrder = isChildrenDrawingOrderEnabled();
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder ?
getChildDrawingOrder(childrenCount, i) : i;
final View child = children[childIndex];
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// 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);
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
mLastTouchDownIndex = childIndex;
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
//注意下面兩句,如果有子View處理了點(diǎn)擊事件,則newTouchTarget會(huì)被賦值,
//同時(shí)alreadyDispatchedToNewTouchTarget也會(huì)為true,這兩個(gè)變量是直接影響下面的代碼邏輯的。
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
}
}
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.
//這里如果當(dāng)前ViewGroup攔截了事件,或者其子View的onTouchEvent都返回了false,則事件會(huì)由ViewGroup處理
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
//這里就是ViewGroup對(duì)點(diǎn)擊事件的處理
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it. Cancel touch targets if necessary.
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;
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;
}
}
// Update list of touch targets for pointer up or cancel, if needed.
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);
}
}
if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}
下面再看ViewGroup對(duì)點(diǎn)擊事件的處理
Code:ViewGroup#dispatchTransformedTouchEvent
/**
* Transforms a motion event into the coordinate space of a particular child view,
* filters out irrelevant pointer ids, and overrides its action if necessary.
* If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
*/
private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
View child, int desiredPointerIdBits) {
final boolean handled;
// Canceling motions is a special case. We don't need to perform any transformations
// or filtering. The important part is the action, not the contents.
final int oldAction = event.getAction();
if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
event.setAction(MotionEvent.ACTION_CANCEL);
if (child == null) {
//這里就是ViewGroup對(duì)點(diǎn)擊事件的處理,其調(diào)用了View的dispatchTouchEvent方法
handled = super.dispatchTouchEvent(event);
} else {
handled = child.dispatchTouchEvent(event);
}
event.setAction(oldAction);
return handled;
}
// Calculate the number of pointers to deliver.
final int oldPointerIdBits = event.getPointerIdBits();
final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
// If for some reason we ended up in an inconsistent state where it looks like we
// might produce a motion event with no pointers in it, then drop the event.
if (newPointerIdBits == 0) {
return false;
}
// If the number of pointers is the same and we don't need to perform any fancy
// irreversible transformations, then we can reuse the motion event for this
// dispatch as long as we are careful to revert any changes we make.
// Otherwise we need to make a copy.
final MotionEvent transformedEvent;
if (newPointerIdBits == oldPointerIdBits) {
if (child == null || child.hasIdentityMatrix()) {
if (child == null) {
handled = super.dispatchTouchEvent(event);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
event.offsetLocation(offsetX, offsetY);
handled = child.dispatchTouchEvent(event);
event.offsetLocation(-offsetX, -offsetY);
}
return handled;
}
transformedEvent = MotionEvent.obtain(event);
} else {
transformedEvent = event.split(newPointerIdBits);
}
// Perform any necessary transformations and dispatch.
if (child == null) {
handled = super.dispatchTouchEvent(transformedEvent);
} else {
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
再看
Code:View#dispatchTouchEvent
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchTouchEvent(MotionEvent event) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
if (onFilterTouchEventForSecurity(event)) {
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
return true;
}
if (onTouchEvent(event)) {
return true;
}
}
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
return false;
}
這段代碼比較簡(jiǎn)單,View對(duì)事件的處理是這樣的:如果設(shè)置了OnTouchListener就調(diào)用onTouch,否則就直接調(diào)用onTouchEvent,而onClick是在onTouchEvent內(nèi)部通過(guò)performClick觸發(fā)的。簡(jiǎn)單來(lái)說(shuō),事件如果被ViewGroup攔截或者子View的onTouchEvent都返回了false,則事件最終由ViewGroup處理。
3.無(wú)人處理的點(diǎn)擊事件
如果一個(gè)點(diǎn)擊事件,子View的onTouchEvent返回了false,則父View的onTouchEvent會(huì)被直接調(diào)用,以此類推。如果所有的View都不處理,則最終會(huì)由Activity來(lái)處理,這個(gè)時(shí)候,Activity的onTouchEvent會(huì)被調(diào)用。這個(gè)問(wèn)題已經(jīng)在1和2中做了說(shuō)明。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android中父View和子view的點(diǎn)擊事件處理問(wèn)題探討
- Android中捕獲TTextView文本中的鏈接點(diǎn)擊事件方法
- 簡(jiǎn)單講解Android開(kāi)發(fā)中觸摸和點(diǎn)擊事件的相關(guān)編程方法
- Android如何防止多次點(diǎn)擊事件
- Android中捕捉menu按鍵點(diǎn)擊事件的方法
- Android使用RecyclerView實(shí)現(xiàn)自定義列表、點(diǎn)擊事件以及下拉刷新
- Android 中ListView的Item點(diǎn)擊事件失效的快速解決方法
- Android開(kāi)發(fā)在輪播圖片上加入點(diǎn)擊事件的方法
- Android中EditText的drawableRight屬性設(shè)置點(diǎn)擊事件
- Android點(diǎn)擊事件的實(shí)現(xiàn)方式
相關(guān)文章
Android解決viewpager嵌套滑動(dòng)沖突并保留側(cè)滑菜單功能
這篇文章主要介紹了 解決viewpager嵌套滑動(dòng)沖突,并保留側(cè)滑菜單功能,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-06-06
Android應(yīng)用開(kāi)發(fā)中數(shù)據(jù)的保存方式總結(jié)
這篇文章主要介紹了Android應(yīng)用開(kāi)發(fā)中數(shù)據(jù)的保存方式總結(jié),包括對(duì)ROM、SD卡、SharedPreference這三種方式實(shí)現(xiàn)的核心代碼的精選,需要的朋友可以參考下2016-02-02
flutter實(shí)現(xiàn)點(diǎn)擊事件
這篇文章主要為大家詳細(xì)介紹了flutter實(shí)現(xiàn)點(diǎn)擊事件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-08-08
Android點(diǎn)擊Button實(shí)現(xiàn)功能的幾種方法總結(jié)
當(dāng)Button有多個(gè)或者Button的使用次數(shù)很多時(shí),我們需要采用綁定監(jiān)聽(tīng)器的做法,其實(shí),綁定監(jiān)聽(tīng)器也有幾種方法,不過(guò),我在這里就不一一列舉了,畢竟那些方法在實(shí)際的應(yīng)用中也不常見(jiàn)2013-10-10
Android中FlowLayout組件實(shí)現(xiàn)瀑布流效果
大家好,本篇文章主要講的是Android中FlowLayout組件實(shí)現(xiàn)瀑布流效果,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下2022-01-01
Android中SwipeBack實(shí)現(xiàn)右滑返回效果
這篇文章主要介紹了Android中SwipeBack實(shí)現(xiàn)右滑返回效果的相關(guān)資料,需要的朋友可以參考下2016-02-02
Android開(kāi)發(fā)之ListView的head消失頁(yè)面導(dǎo)航欄的漸變出現(xiàn)和隱藏
這篇文章主要介紹了Android開(kāi)發(fā)之ListView的head消失頁(yè)面導(dǎo)航欄的漸變出現(xiàn)和隱藏的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-11-11
android studio實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器功能
這篇文章主要為大家詳細(xì)介紹了android studio實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-05-05
清楚詳解Android?進(jìn)程間圖傳遞圖形buffer原理
這篇文章主要為大家清楚的詳解了Android?進(jìn)程間圖傳遞圖形buffer原理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02

