最近做了一个类似桌面应用图标可以点击,长按拖动效果,然后研究了下android触摸事件机制。
Android中的事件分为按键事件和触摸事件,这里对触摸事件进行阐述。Touch事件是由一个ACTION_DOWN,n个ACTION_MOVE,一个ACTION_UP组成onClick,onLongClick,onScroll等事件。Android中的控件都是继承View这个基类的,而控件分为两种:一种是继承View不能包含其他控件的控件;一种是继承ViewGroup可以包含其他控件的控件,暂且称为容器控件,比如ListView,GridView,LinearLayout等。
这里先对几个函数讲解下。
Ø public boolean dispatchTouchEvent (MotionEventev) 这个方法分发TouchEvent
Ø public booleanonInterceptTouchEvent(MotionEvent ev) 这个方法拦截TouchEvent
Ø public boolean onTouchEvent(MotionEvent ev) 这个方法处理TouchEvent
其中view类中有dispatchTouchEvent和onTouchEvent两个方法,ViewGroup继承View,而且还新添了一个onInterceptTouchEvent方法。Activity中也无onInterceptTouchEvent方法,但有另外两种方法。我们可以发现上面3个方法都是返回boolean,那各代表什么意思呢?
public boolean dispatchTouchEvent (MotionEvent ev)
Activity中解释:
Called to process touch screen events.You can override this to intercept all touch screen events before they aredispatched to the window. Be sure to call this implementation for touch screenevents that should be handled normally.
Parameters
ev |
The touch screen event. |
Returns
· boolean Return true if this event was consumed.
它会被调用处理触摸屏事件,可以重写覆盖此方法来拦截所有触摸屏事件在这些事件分发到窗口之前。通常应该处理触摸屏事件,一定要调用这个实现。当返回值为true时,表示这个事件已经被消费了。例如在TextActivity中dispatchTouchEvent在ACTION_MOVE返回true,运行结果如下:
也就是它并没有把那ACTION_MOVE分发下去。
public boolean onInterceptTouchEvent (MotionEvent ev)
Implementthis method to intercept all touch screen motion events. This allows you towatch events as they are dispatched to your children, and take ownership of thecurrent gesture at any point.
Usingthis function takes some care, as it has a fairly complicated interaction with View.onTouchEvent(MotionEvent),and using it requires implementing that method as well as this one in thecorrect way. Events will be received in the following order:
1. You will receive the down event here.
2. The down event will be handled either by a child of this viewgroup, or given to your own onTouchEvent() method to handle; this means youshould implement onTouchEvent() to return true, so you will continue to see therest of the gesture (instead of looking for a parent view to handle it). Also,by returning true from onTouchEvent(), you will not receive any followingevents in onInterceptTouchEvent() and all touch processing must happen inonTouchEvent() like normal.
3. For as long as you return false from this function, eachfollowing event (up to and including the fin