Android触摸事件机制

本文详细探讨了Android触摸事件的处理机制,包括ACTION_DOWN、ACTION_MOVE和ACTION_UP等事件的传递过程。从Activity到ViewGroup,再到View,分析了dispatchTouchEvent、onInterceptTouchEvent和onTouchEvent的作用和返回值的意义。通过不同场景的示例,展示了触摸事件如何被消费以及如何影响onClick和onLongClick事件的触发。文章最后提供了源码下载链接,帮助开发者更好地理解和处理Android触摸事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


最近做了一个类似桌面应用图标可以点击,长按拖动效果,然后研究了下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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值