關於這個返回值的問題,上一篇文章中那位大牛有很詳細的解釋。原文鏈接:http://www.cnblogs.com/kingcent/archive/2011/03/08/1977064.html
我讀了之後,結合調試程序,是很好的理解了,所以就不再狗尾續貂了。呵呵
nInterceptTouchEvent()用於處理事件並改變事件的傳遞方向。處理事件這個不用說了,你在函數內部編寫代碼處理就可以了。而決定傳遞方向的是返回值,返回爲false時事件會傳遞給子控件的onInterceptTouchEvent();返回值爲true時事件會傳遞給當前控件的onTouchEvent(),而不在傳遞給子控件,這就是所謂的Intercept(截斷)。
onTouchEvent() 用於處理事件,返回值決定當前控件是否消費(consume)了這個事件。可能你要問是否消費了又區別嗎,反正我已經針對事件編寫了處理代碼?答案是有區別!比如ACTION_MOVE或者ACTION_UP發生的前提是一定曾經發生了ACTION_DOWN,如果你沒有消費ACTION_DOWN,那麼系統會認爲ACTION_DOWN沒有發生過,所以ACTION_MOVE或者ACTION_UP就不能被捕獲。
01 |
<? xml version = "1.0" encoding = "utf-8" ?> |
03 |
android:orientation = "vertical" |
04 |
android:layout_width = "fill_parent" |
05 |
android:layout_height = "fill_parent" > |
06 |
< com.touchstudy.LayoutView2 |
07 |
android:orientation = "vertical" |
08 |
android:layout_width = "fill_parent" |
09 |
android:layout_height = "fill_parent" |
10 |
android:gravity = "center" > |
11 |
< com.touchstudy.MyTextView |
12 |
android:layout_width = "wrap_content" |
13 |
android:layout_height = "wrap_content" |
16 |
android:textSize = "40sp" |
17 |
android:textStyle = "bold" |
18 |
android:background = "#FFFFFF" |
19 |
android:textColor = "#0000FF" /> |
20 |
</ com.touchstudy.LayoutView2 > |
21 |
</ com.touchstudy.LayoutView1 > |
在沒有重寫onInterceptTouchEvent()和onTouchEvent()的情況下(他們的返回值都是false), 對上面這個佈局,MotionEvent事件的傳遞順序如下:
當某個控件的onInterceptTouchEvent()返回值爲true時,就會發生截斷,事件被傳到當前控件的onTouchEvent()。如我們將LayoutView2的onInterceptTouchEvent()返回值爲true,則傳遞流程變成:
如果我們同時將LayoutView2的onInterceptTouchEvent()和onTouchEvent()設置成true,那麼LayoutView2將消費被傳遞的事件,同時後續事件(如跟着ACTION_DOWN的ACTION_MOVE或者ACTION_UP)會直接傳給LayoutView2的onTouchEvent(),不傳給其他任何控件的任何函數。同時傳遞給子空間一個ACTION_CANCEL事件。傳遞流程變成(圖中沒有畫出ACTION_CANCEL事件):