編輯:關於Android編程
我們首先從一個簡單的例子開始分析
button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { System.out.println("執行onClick"); } }); button.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { System.out.println("執行onTouch的"+event.getAction()); return false; } });
這段代碼經常出現在我們綁定按鈕監聽事件的情況下,但是你能確定當同時為按鈕綁定onClick和onTouch事件的情況下會首先執行哪個事件麼?我們來看看輸出結果:
04-29 22:52:43.411: I/System.out(845): 執行onTouch的0
04-29 22:52:43.481: I/System.out(845): 執行onTouch的1
04-29 22:52:43.572: I/System.out(845): 執行onClick
也許你的手會抖幾下,那麼你的輸出結果將會多幾個執行onTouch的2的值;
但是不管怎麼說,首先還是會先執行的onTouch方法,隨後onTouch執行結束才會執行onClick方法,除此之外,我們還發現onTouch方法是有返回值的,上面實例中,返回值是false,假如我們將該返回值設置為true的話,程序的輸出結果是:
04-29 23:25:15.082: I/System.out(966): 執行onTouch的0
04-29 23:25:15.161: I/System.out(966): 執行onTouch的1
不管你怎麼點擊按鈕,都不會執行onClick方法,這更加印證了onTouch優先於onClick方法執行,當onTouch返回值設置為true的時候我們可以理解為onTouch方法將事件消費掉了,不再會傳遞下去;
平常的應用就是這樣啦,接下來從源碼的角度分析一下造成這種情況的原因:
首先分析之前應該明白的一點就是觸摸屏事件首先傳遞到的是ViewGroup的,他是我們平常的各種布局的父類或者間接父類,這點可以從android官方文檔中看到:
可以看出,LinearLayout以及各種布局文件都是他的子類,ViewGroup是一組View的集合,他包含很多子View和子ViewGroup,因此在探討ViewGroup的事件分發機制之前我們首先應該看看View的事件分發機制;
首先應該明白的是每當觸摸一個控件的時候都會調用該控件的dispatchTouchEvent方法,以上面的Button類為例,發現Button類中不存在dispatchTouchEvent方法,那麼就到他的父類TextView中尋找,發現TextView中也不存在這個方法,隨後到TextView的父類View中去尋找,終於找到啦!
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; }
這段源碼的核心代碼在第9行,他會首先查看下li是否為null以及li中的mOnTouchListener是否為null,(mViewFlags & ENABLED_MASK)==ENABLE判斷當前控件是否是ENABLE的,那麼這裡的li到底是什麼呢?第8行看到,li是等於 mListenerInfo的ListenerInfo對象,那麼mListenerInfo是在哪裡賦值的呢?
ListenerInfo getListenerInfo() { if (mListenerInfo != null) { return mListenerInfo; } mListenerInfo = new ListenerInfo(); return mListenerInfo; } 可以看到是調用getListenerInfo方法來生成的,那麼li中的屬性mOnTouchListener是在哪裡賦值的呢? public void setOnTouchListener(OnTouchListener l) { getListenerInfo().mOnTouchListener = l; }可以看到是調用getListenerInfo方法來生成的,那麼li中的屬性mOnTouchListener是在哪裡賦值的呢?
public void setOnTouchListener(OnTouchListener l) { getListenerInfo().mOnTouchListener = l; }發現就是將我們平常使用setOnTouchListener的參數設置為了li的mOnTouchListener屬性,那麼當li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED為true的時候會執行最後一個條件判斷語句,也就是我們在setOnTouchListener裡面經常重寫的那個方法onTouch啦,這個方法會有一個返回值,當返回值為true的時候執行if語句塊中的內容,直接返回true,那麼dispatchTouchEvent方法執行結束,也就是整個事件分發已經結束了,所以上面例子中當我們將onTouch方法的返回值設置為true的時候,並不會執行onClick方法,因為程序在這個if語句塊中已經返回了;
那麼我們有理由相信第14行的if語句塊中的onTouchEvent方法肯定與onClick方法有關系,來看看源碼:
public boolean onTouchEvent(MotionEvent event) { final int viewFlags = mViewFlags; if ((viewFlags & ENABLED_MASK) == DISABLED) { if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { setPressed(false); } // A disabled view that is clickable still consumes the touch // events, it just doesn't respond to them. return (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); } if (mTouchDelegate != null) { if (mTouchDelegate.onTouchEvent(event)) { return true; } } if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { switch (event.getAction()) { case MotionEvent.ACTION_UP: 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); } if (!mHasPerformedLongPress) { // 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)) { performClick(); } } } if (mUnsetPressedState == null) { mUnsetPressedState = new UnsetPressedState(); } if (prepressed) { postDelayed(mUnsetPressedState, ViewConfiguration.getPressedStateDuration()); } else if (!post(mUnsetPressedState)) { // If the post failed, unpress right now mUnsetPressedState.run(); } removeTapCallback(); } break; case MotionEvent.ACTION_DOWN: mHasPerformedLongPress = false; if (performButtonActionOnTouchDown(event)) { break; } // Walk up the hierarchy to determine if we're inside a scrolling container. boolean isInScrollingContainer = isInScrollingContainer(); // For views inside a scrolling container, delay the pressed feedback for // a short period in case this is a scroll. if (isInScrollingContainer) { mPrivateFlags |= PFLAG_PREPRESSED; if (mPendingCheckForTap == null) { mPendingCheckForTap = new CheckForTap(); } postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); } else { // Not inside a scrolling container, so show the feedback right away setPressed(true); checkForLongClick(0); } break; case MotionEvent.ACTION_CANCEL: setPressed(false); removeTapCallback(); removeLongPressCallback(); break; case MotionEvent.ACTION_MOVE: final int x = (int) event.getX(); final int y = (int) event.getY(); // Be lenient about moving outside of buttons if (!pointInView(x, y, mTouchSlop)) { // Outside button removeTapCallback(); if ((mPrivateFlags & PFLAG_PRESSED) != 0) { // Remove any future long press/tap checks removeLongPressCallback(); setPressed(false); } } break; } return true; } return false; }
這個方法有點長,我們僅看核心部分,首先第4行的if語句的作用在於可能當前View是disabled的,但是仍然是可點擊的,這種情況下我們同樣需要消費掉這個Touch事件,只不過不對這個Touch事件做任何事情而已,只是返回true而已;第20行,如果當前控件是可點擊的話,則進入switch裡面判斷當前事件的類型,我們進入MotionEvent.ACTION_UP裡面查看將會發現經過層層if判斷,最終將會執行第54行的performClick方法,進入這個方法裡面看看執行了些什麼操作:
public boolean performClick() { sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); ListenerInfo li = mListenerInfo; if (li != null && li.mOnClickListener != null) { playSoundEffect(SoundEffectConstants.CLICK); li.mOnClickListener.onClick(this); return true; } return false; }第5行判斷li以及他的屬性mOnClickListener是否為null,聰明的你一定會猜到mOnClickListener的賦值操作和前面的mOnTouchListener將是一樣的
public void setOnClickListener(OnClickListener l) { if (!isClickable()) { setClickable(true); } getListenerInfo().mOnClickListener = l; }沒錯吧,最後執行他的onClick方法就行啦,當然平時我們是重寫這個方法的;
一切都變的那麼明了了,其實如果說onClick方法執行在onTouch方法之後具體有多後呢?剛剛就已經看出來了,在我們的手指即將離開控件的時候,即MotionEvent.ACTION_UP情況下才會執行onClick方法;
好啦,View的事件分發過程就已經介紹結束啦,我們做個總結一下馬上看看事件是怎麼從ViewGroup傳遞到View的:
首先在每個控件View上面觸發事件的時候都會首先執行dispatchTouchEvent方法,接著在這個方法裡面首先會查看是否有touch事件綁定,有的話直接執行該touch事件的onTouch方法,並且如果onTouch方法返回的是true的話,則dispatchTouchEvent方法直接返回true,執行結束;如果沒有綁定touch事件或者onTouch方法返回false的話,則執行onTouchEvent方法,在這個方法switch的MotionEvent.ACTION_UP這個case情況下調用performClick,進而調用onClick方法執行點擊事件,執行結束之後返回true,最後dispatchTouchEvent方法返回,事件分發結束;
前面已經提到過事件是從ViewGroup傳遞到View的,那麼這個過程又是怎麼的呢?
來,我們看個例子:
button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { System.out.println("執行了Button的onClick方法"); } }); relativeLayout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { System.out.println("執行了RelativeLayout的onTouch方法,action為: "+arg1.getAction()); return false; } });
我們分別為Button以及RealtiveLayout設置了Click監聽事件
點擊button的輸出為:
04-30 02:46:45.131: I/System.out(1164): 執行了Button的onClick方法
點擊屏幕空白區域的輸出為:
04-30 02:52:57.305: I/System.out(1220): 執行了RelativeLayout的onTouch方法,action為: 0
也就是當我們直接點擊button按鈕的時候是不會執行RelativeLayout的onTouch方法的,在這裡Button按鈕相當於是View,而RelativeLayout相當於ViewGroup,前面已經提到事件是從ViewGroup傳遞到View的,事實依據就是:
假如我們認為是從View傳遞到ViewGroup,那麼只要我們找到一種情況就是點擊View控件的時候觸發的只是ViewGroup綁定的方法而不是View綁定的方法的話,我們就可以認為是ViewGroup消費了事件,因此事件是ViewGroup到View的,接下來舉出這樣的例子:
我們自己來實現一個RelativeLayout,並且重寫onInterceptTouchEvent方法,這個方法的原型是在ViewGroup裡面的,原型見下:
public boolean onInterceptTouchEvent(MotionEvent ev) { return false; }就是這麼簡單,只是返回false而已;
我們自定義的RelativeLayout命名為MyRelativeLayout:
public class MyRelativeLayout extends RelativeLayout{ public MyRelativeLayout(Context context) { super(context); } public MyRelativeLayout(Context context, AttributeSet attrs) { super(context,attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return true; } }可見我們把onInterceptTouchEvent的返回值修改成了true,在將自定義布局引入到布局文件之後,重新執行程序會發現不管我們是點擊button按鈕還是點擊空白區域輸出的結果都是:
04-30 03:12:36.901: I/System.out(1310): 執行了RelativeLayout的onTouch方法,action為: 0
這也就是說當我們把onInterceptTouchEvent的返回值修改成了true,可以理解為當前布局也就是ViewGroup消費了事件,事件沒有再向下傳遞了,也就說明了事件是從ViewGroup傳遞到View的啦!
那麼上面我們說過觸發View控件的事件首先會觸發其dispatchTouchEvent事件,那麼其實實際上呢,觸發這個方法的本質上就已經可以說成是ViewGroup觸發的啦,那麼我們進入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) { 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; 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(); 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. if (mFirstTouchTarget == null) { // No touch targets so treat this as an ordinary 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; }同樣源碼好長,我們只看核心:
第46行我們看到if判斷的條件是只要canceled和intercepted都為false的話,就會執行if語句塊的內容,而intercepted的值正是前面我們通過onInterceptTouchEvent方法返回的值,那麼我們有理由相信按鈕的點擊事件肯定是在這個if語句塊中執行的,因為前面我們將onInterceptTouchEvent的返回值改為true之後,if不會執行其語句塊,也就意味著直接屏蔽了按鈕點擊事件了,在if語句塊中經過層層計算最後到達第85行執行了dispatchTransformedTouchEvent方法,這個方法也屬於ViewGroup,在這個方法裡面肯定會出現調用View的dispatchTouchEvent方法,我們可以看看dispatchTransformedTouchEvent的源碼:
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) { 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; }同樣挺長的,我們只看重點,在第11行、13行、37行、43行、56行、65行可能會執行不同判斷條件下的View的dispatchTouchEvent方法,但是不管怎麼說這個方法是從ViewGroup方法裡面的dispatchTouchEvent調用的,接下來的事件分發就是最開始我們介紹的View的事件分發過程啦,至此整個事件分發過程介紹結束!
總結一下整個事件分發流程是這樣子的:
ViewGroup(所有布局的父類)通過調用自己的dispatchTouchEvent方法,將事件傳遞給自己裡面的View,View自己調用自己的dispatchTouchEvent方法來進行事件處理,細節方面上面已經總結過啦!
1, 特點1, 插入sd卡2, 分為兩部分: sd的公共目錄 sd的私有目錄3, 公共目錄下的文件可以被應用程序共享, 私有目錄下的文件只能被當前應用程序訪問4, 當程序
最近遇到一個問題,因為是新人嘛,項目趕工也比較近,所以老是在加班,把平時工作中遇到的問題統一整理,待到雙休加班的時候,偷閒發表一下。進入正題:我們經常要用到星級評論的效果
網易新聞看起來很簡潔,左邊是一張圖片,右邊是一些文字信息,這樣的排版是十分常見的,給人的感覺就是簡潔明了,下面通過解析網絡json數據並展示到ListView上,來實現同
效果項目地址DraggableTableView所有Cell都可以拖拽。固定第一個Cell限制長按區域實現原理對UITableView添加LongPress手勢 在lon