1泼返、View和ViewGroup之間的關系
在android中,ViewGroup 繼承了View,也就是說android中控件全部是View唠椭,不管是TextView,Button,ImageView還是五大布局等,只不過ViewGroup可以放置其他的View和ViewGroup忍饰,而View是不可以的
2贪嫂、View中的事件序列
在android中,一次操作(點擊艾蓝,觸摸等)會產(chǎn)生一個事件序列力崇,這個事件序列組成部分為:一個MotionEvent.ACTION_DOWN事件,0到多個MotionEvent.ACTION_MOVE事件赢织,一個MotionEvent.ACTION_UP或是MotionEvent.ACTION_CANCEL事件
事件分發(fā)機制涉及的主要方法
dispatchTouchEvent(MotionEvent ev): 對事件進行分發(fā)亮靴,返回值表示是否消費當前事件,返回值受該View的OnTouchEvent()和子View的dispatchTouchEvent()方法返回值影響
onInterceptTouchEvent(MotionEvent ev): 該方法只存在于ViewGroup中于置,返回值表示是否對當前事件進行攔截
onTouchEvent(MotionEvent ev): 該方法返回值表示是否消費當前事件
3茧吊、詳細測試
兩個簡單的view分別為MRelativeLayout extends RelativeLayout和MTextView extends TextView
3.1 測試一:父View對事件攔截,并在onTouchEvent()對事件處理八毯,這個時候父view的dispatchTouchEvent返回值是為true的
3.2 測試二:父View對事件攔截搓侄,但在onTouchEvent()對事件沒有處理
3.3 測試三:父View對事件不攔截,子View對事件進行處理
3.4 測試四:父view對事件不攔截话速,子view對事件也不處理
3.5 簡要總結(jié)
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean isConsume = false;
if(onInterceptTouchEvent(ev)){
isConsume = onTouchEvent(ev);
}else{
isConsume = childView.dispatchTouchEvent(ev);
}
return isConsume;
}
一個事件產(chǎn)生后讶踪,先由viewgroup的dispatchTouchevent對事件進行分發(fā),dispatchTouchevent先調(diào)用onInterceptTouchEvent查看自己是否攔截了事件泊交, 1): 如果攔截了乳讥,則再看自己的onTouchEvent對事件是否進行了消費處理柱查,如果自己處理了,則返回true云石,事件到這里就結(jié)束了唉工;如果沒有處理,那么該事件則會往父view拋(onTouchEvent)留晚,如果父view都沒有處理酵紫,則拋向window直到activity的onTouchEvent;2) 如果ViewGroup沒有攔截事件错维,則交給子View的dispatchTouchEvent()來進行分發(fā),如果子View也是ViewGroup,分發(fā)邏輯和上面一樣橄唬,如果子View是一個View赋焕,那么則直接進入View的onTouchEvent()來確定事件是否被消耗掉,如果消耗了仰楚,返回true隆判,如果沒有消耗,則依次往父view拋僧界,直到交給activity處理侨嘀。
4、View源碼分析
4.1 在android中捂襟,當用戶觸摸設備產(chǎn)生事件(MotionEvent)的時候咬腕,事件會先傳遞到activity,然后activity傳給其內(nèi)部的window葬荷,window再傳給decorview涨共,decorview傳給布局中的相關view。
4.2 Activity.dispatchTouchEvent()
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();// 空實現(xiàn)
}
// window初始化在attach()方法中
if (getWindow().superDispatchTouchEvent(ev)) {
// 事件被Activity的下級給消費掉了
return true;
}
// 事件在Activity的下級中沒有被消費掉宠漩,交由Activity自己來處理
return onTouchEvent(ev);
}
4.3 Window.superDispatchTouchEvent()
Window是一個抽象類举反,根據(jù)Window類的注釋能夠知道,在整個android系統(tǒng)中扒吁,window只有一個子類:PhoneWindow,所以這里主要是看PhoneWindow對這個方法的實現(xiàn)火鼻。
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
// mDecor是一個DecorView
return mDecor.superDispatchTouchEvent(event);
}
可以看到,PhoneWindow把對事件的處理權限交給了DecorView雕崩,那么DecorView是什么呢魁索?又是怎么初始化的呢?
4.4 DecorView
private final class DecorView extends FrameLayout implements RootViewSurfaceTaker 晨逝,
從這個定義可以看到DecorView其實就是一個FrameLayout而已蛾默。
4.5 DecorView的初始化過程
在activity中設置View是通過setContentView()方法來完成的,所以我們從這里開始分析一下是怎么操作的捉貌。
Activity.setContentView()
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
PhoneWindow.setContentView()
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
// 這里負責DecorView和mContentParent的初始化支鸡,至于mContentParent冬念,它是:
// ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
// ID_ANDROID_CONTENT = com.android.internal.R.id.content
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {// Activity過渡動畫
view.setLayoutParams(params);
final Scene newScene = new Scene(mContentParent, view);
transitionTo(newScene);
} else {
// 把我們自己的布局添加到mContentParent容器中
mContentParent.addView(view, params);
}
//.........
}
PhoneWindow.installDecor()
private void installDecor() {
private void installDecor() {
if (mDecor == null) {
// 初始化DecorView
mDecor = generateDecor();
// .........
}
if (mContentParent == null) {
// 初始化ViewGroup,也就是我們定義的布局的父容器
mContentParent = generateLayout(mDecor);
// .....................
}
}
PhoneWindow.generateDecor()
protected DecorView generateDecor() {
return new DecorView(getContext(), -1);
}
PhoneWindow.generateLayout()
protected ViewGroup generateLayout(DecorView decor) {
//............
mDecor.startChanging();
// 這個名為in的View,用來決定整個window會顯示成什么樣子(Theme),
View in = mLayoutInflater.inflate(layoutResource, null);
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
mContentRoot = (ViewGroup) in;
// 從in這個view中找到我們自己定義的布局的父容器
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
//....................
mDecor.finishChanging();
return contentParent;
}
這里貼兩個名為in的View對應的布局文件
R.layout.screen_custom_title.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:fitsSystemWindows="true">
<!-- Popout bar for action modes -->
<ViewStub android:id="@+id/action_mode_bar_stub"
android:inflatedId="@+id/action_mode_bar"
android:layout="@layout/action_mode_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="?attr/actionBarTheme" />
<FrameLayout android:id="@android:id/title_container"
android:layout_width="match_parent"
android:layout_height="?android:attr/windowTitleSize"
android:transitionName="android:title"
style="?android:attr/windowTitleBackgroundStyle">
</FrameLayout>
<FrameLayout android:id="@android:id/content"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:foregroundGravity="fill_horizontal|top"
android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>
R.layout.screen_simple.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:fitsSystemWindows="true">
<!-- Popout bar for action modes -->
<ViewStub android:id="@+id/action_mode_bar_stub"
android:inflatedId="@+id/action_mode_bar"
android:layout="@layout/action_mode_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="?attr/actionBarTheme" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="?android:attr/windowTitleSize"
style="?android:attr/windowTitleBackgroundStyle">
<TextView android:id="@android:id/title"
style="?android:attr/windowTitleStyle"
android:background="@null"
android:fadingEdge="horizontal"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
<FrameLayout android:id="@android:id/content"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:foregroundGravity="fill_horizontal|top"
android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>
關于DectorView的初始化過程就是這樣了牧挣,從這里也可以看出來整個View的層級關系:
Activity->window->decorview->SystemLayout->contentView->應用自定義布局對應view
4.6 繼續(xù)事件分發(fā):DecorView.superDispatchTouchEvent()
public boolean superDispatchTouchEvent(MotionEvent event) {
// 因為DecorView是一個FrameLayout,因而這里就是ViewGroup.dispatchTouchEvent()
return super.dispatchTouchEvent(event);
}
4.7 ViewGroup.dispatchTouchEvent()
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
// If the event targets the accessibility focused view and this is it, start
// normal event dispatch. Maybe a descendant is what will handle the click.
if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
ev.setTargetAccessibilityFocus(false);
}
boolean handled = false;
// 是否對事件進行分發(fā)急前,如果窗口被遮擋,直接返回false瀑构,否則返回true
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.
// 如果監(jiān)聽到ACTION_DOWN事件裆针,表明一次觸摸的開始,那么一些東西就要清空和重置了寺晌。
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
final boolean intercepted;// 是否對事件進行了攔截
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
// mFirstTouchTarget != null這個意思是:ViewGroup本身不攔截事件世吨,而是把事件傳給子View處理了。
// 也就是說呻征,一旦ViewGroup本身對事件進行了攔截處理耘婚,那么mFirstTouchTarget = null
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
// FLAG_DISALLOW_INTERCEPT:requestDisallowInterceptTouchEvent()中設置
if (!disallowIntercept) {// 允許對事件進行攔截處理
intercepted = onInterceptTouchEvent(ev);//
ev.setAction(action); // restore action in case it was changed
} else {// 不允許對事件攔截
intercepted = false;
}
} else {// 如果ViewGroup本身對事件進行了處理,那么ACTION_MOVE,ACTION_UP等事件就直接被ViewGroup攔截了陆赋,不會再傳給子View了
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
// 以上部分總結(jié)一下:當接收到ACTION_DOWN事件的時候沐祷,會把一些東西清空和重置
// 對于一次觸摸會產(chǎn)生一個事件序列,如果接收到action_down事件或者事件交給了子View來處理攒岛,
// 在允許對事件進行攔截的情況下赖临,ViewGroup的onInterceptTouchEvent()會被執(zhí)行到并且只會執(zhí)行到一次(ACTION_DOWN事件)。
// 所以這里要注意一點灾锯,如果ViewGroup本身對ACTION_DOWN事件進行了攔截兢榨,
// 那么對于ACTION_MOVE,ACTION_UP等事件,因為mFirstTouchTarget != null為false挠进,
// actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null則返回false色乾,
// 那么intercepted一直為true,因而這些事件是不會再傳給子view的领突。
// 從這里可以看到:
// 如果ViewGroup本身對事件進行了處理暖璧,mFirstTouchTarget != null為false,那么onInterceptTouchEvent()只會被執(zhí)行一次,
// 后續(xù)事件ACTION_MOVE,ACTION_UP等都不會進入 onInterceptTouchEvent()君旦;
// 而如果ViewGroup本事沒有對事件進行處理澎办,而是交給了子View來處理蔑歌,
// 那么mFirstTouchTarget != null為true手蝎,則事件序列中的每個事件都會進入onInterceptTouchEvent()
// 驗證測試3.3結(jié)果
// If intercepted, start normal event dispatch. Also if there is already
// a view that is handling the gesture, do normal event dispatch.
if (intercepted || mFirstTouchTarget != null) {
// ViewGroup本身對事件進行了攔截
ev.setTargetAccessibilityFocus(false);
}
// 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;
if (!canceled && !intercepted) {
// 事件沒有取消也沒有被ViewGroup本身攔截:事件分發(fā)給子View
// If the event is targeting accessiiblity focus we give it to the
// view that has accessibility focus and if it does not handle it
// we clear the flag and dispatch the event to all children as usual.
// We are looking up the accessibility focused host to avoid keeping
// state since these events are very rare.
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
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.
// 對子view進行排序處理,最上層到最下層
final ArrayList<View> preorderedList = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
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);
// 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;
}
// 子View不可見沒有播放動畫碎紊,或者觸摸點不在子view上
if (!canViewReceivePointerEvents(child)// 子view既不可見或也沒有播放動畫
|| !isTransformedTouchPointInView(x, y, child, null)) {// 觸摸點在子view外
ev.setTargetAccessibilityFocus(false);
continue;
}
// 子View正在接收touch事件
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;
}
// 到這里newTouchTarget還是為null的
resetCancelNextUpFlag(child);
// 事件交由子view來處理了恕稠,這里的child是不為null的
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();
// mFirstTouchTarget 被賦值琅绅,驗證了mFirstTouchTarget!=null表示事件交由子view來消費
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
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();
}
// 事件交由子View來處理,但是卻沒有找到這樣的子view
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) {//
// No touch targets so treat this as an ordinary view.
// 這里的child為null鹅巍,因而直接執(zhí)行view的dispatchTouchEvent()方法千扶,對事件進行處理料祠,不再傳給子view
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;
}
4.8 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) {
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) {// 子View不存在,則交給ViewGroup的父類View來處理了
handled = super.dispatchTouchEvent(transformedEvent);
} else {//子View存在
final float offsetX = mScrollX - child.mLeft;
final float offsetY = mScrollY - child.mTop;
transformedEvent.offsetLocation(offsetX, offsetY);
if (! child.hasIdentityMatrix()) {
transformedEvent.transform(child.getInverseMatrix());
}
// 子view dispatchTouchEvent()
handled = child.dispatchTouchEvent(transformedEvent);
}
// Done.
transformedEvent.recycle();
return handled;
}
4.8 ViewGroup.addTouchTarget()
private TouchTarget addTouchTarget(View child, int pointerIdBits) {
TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
target.next = mFirstTouchTarget;
// mFirstTouchTarget 賦值了
mFirstTouchTarget = target;
return target;
}
4.9 View.dispatchTouchEvent()
public boolean dispatchTouchEvent(MotionEvent event) {
// If the event should be handled by accessibility focus first.
if (event.isTargetAccessibilityFocus()) {
// We don't have focus or no virtual descendant has it, do not handle the event.
if (!isAccessibilityFocusedViewOrHost()) {
return false;
}
// We have focus and got the event, then use normal event dispatch.
event.setTargetAccessibilityFocus(false);
}
boolean result = false;
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Defensive cleanup for new gesture
stopNestedScroll();
}
if (onFilterTouchEventForSecurity(event)) {
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;
// 優(yōu)先執(zhí)行OnTouchListener.onTouch()
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {
result = true;
}
// 在OnTouchListener為null時才執(zhí)行onTouchEvent
// 在onTouchEvent()中的ACTION_UP事件中判斷ClickListener是否不為null澎羞,
// 如果 不為null髓绽,則執(zhí)行onClick()
if (!result && onTouchEvent(event)) {
result = true;
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
// Clean up after nested scrolls if this is the end of a gesture;
// also cancel it if we tried an ACTION_DOWN but we didn't want the rest
// of the gesture.
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;
}
以上,是View事件分發(fā)機制的基本過程妆绞,總得來說顺呕,當設備接收到事件的時候,先由activity來進行分發(fā)(dispatchTouchEvent())給window括饶,window接收到事件的時候交給DecorView來處理株茶,而DecorView本身是一個ViewGroup,因而存在自己攔截處理或是分發(fā)給子view來處理等幾種情況图焰,如果自己進行攔截處理(OnInterceptTouchEvent() return true),那么事件最終是否消費取決于ViewGroup.onTouchEvent()忌卤,并且事件是不會再傳給子View的;如果事件交由子view來處理楞泼,那么事件是否消費則由子view來定了,這個邏輯基本和現(xiàn)有邏輯一致笤闯。view對于事件的處理堕阔,是直接由onTouchEvent來決定的,在View.onTouchEvent()中首先會判斷是否有TouchListener颗味,如果有超陆,則直接執(zhí)行onTouch,如果沒有浦马,則再看clickListener有沒有时呀,有,執(zhí)行onClick晶默。