ViewGroup.onInterceptTouchEvent() onTouchEvent()
原文摘自
:http://blogold.chinaunix.net/u3/113134/showart_2361151.html
ViewGroup
類的
onInterceptTouchEvent(MotionEvent
ev)
分析
實現這個方法去攔截所有的螢幕手勢動作事件。這允許你去查看這些事件當它們被分發到
ViewGroup
的下一級
view
,並且在任何一點能擁有當前的手勢。
使用這個方法要注意
:它與
View.onTouchEvent(MotionEvent)
方法有相當複雜的互動,使用它必須要同樣正確的實現這個方法。事件將會以下面的順序到達:
1、
你將會在這裡接收到
down
事件
2、
Down
事件或者被該
viewGroup
的一個
child
處理,或者將被給到
viewGroup
自己的
onTouchEvent()
方法來處理。這意味著你應該實現
onTouchEvent()
從而可以返回
true
,所以你將繼續看到剩餘的手勢
(
而不是尋找一個
parent view
去處理它
)
。並且,通過從
onTouchEvent()
返回
true
,你將不會在
onInterceptTouchEvent()
中接收到以下任何事件並且所有觸屏處理必須在
onTouchEvent()
中像正常情況一樣發生。
3、
只要從
onInterceptTouchEvent()
返回
false
,接下來的每一個事件
(
截止到
up
並包括最後一個
up)
將會首先被傳遞到這裡,然後到目標
view
的
onTouchEvent()
。
4、
如果從
onInterceptTouchEvent()
返回
true
,你將不會接收到任何以下事件:目標
view
將會接收到相同的事件但是帶著
ACTION_CANCEL
的動作,所有以後的事件將會被傳遞到你的
onTouchEvent()
方法中並且不再在這裡出現。
傳回值:返回
true
從
childernview
那裡偷取動作事件並通過
onTouchEvent()
把它們分發到這個
ViewGroup
。當前的目標
view
將會接收到一個
ACTION_CANCEL
事件,並且將來也不會再有訊息被傳遞到這裡。
ViewGroup
類的
onTouchEvent(MotionEvent
event)
分析
實現這個方法去處理觸屏事件
如果事件被處理則返回
true
,沒有被處理則返回
false
基本的規則是:
1.
down
事件首先會傳遞到
onInterceptTouchEvent()
方法
2.
如果該
ViewGroup
的
onInterceptTouchEvent()
在接收到
down
事件處理完成之後
return false
,那麼後續的
move, up
等事件將繼續會先傳遞給該
ViewGroup
,之後才和
down
事件一樣傳遞給最終的目標
view
的
onTouchEvent()
處理。
3.
如果該
ViewGroup
的
onInterceptTouchEvent()
在接收到
down
事件處理完成之後
return true
,那麼後續的
move, up
等事件將不再傳遞給
onInterceptTouchEvent()
,而是和
down
事件一樣傳遞給該
ViewGroup
的
onTouchEvent()
處理,注意,目標
view
將接收不到任何事件。
4.
如果最終需要處理事件的
view
的
onTouchEvent()
返回了
false
,那麼該事件將被傳遞至其上一層次的
view
的
onTouchEvent()
處理。
5.
如果最終需要處理事件的
view
的
onTouchEvent()
返回了
true
,那麼後續事件將可以繼續傳遞給該
view
的
onTouchEvent()
處理。
註:
Q:
After many experiments with these two onTouchEvent and onTouch i come up
that the onTouch works everywhere you want (I mean if it's activity or
view) as long as you have declare the interface and put the Listener
right! On the other hand onTouchEvent is working only inside a View!
Does I assume right or not?Is this the real difference?
A:Yes you are correct - onTouch()
is used by users
of the View
to get touch events while onTouchEvent()
is used by derived classes
of the View
to get touch events.