Android-ViewGroup的事件机制

本文详细解析了Android中触摸事件在ViewGroup与View之间的传递机制,包括不同触摸事件(如ACTION_DOWN、ACTION_MOVE、ACTION_UP)如何被处理及ViewGroup如何通过特定方法控制事件的拦截。

     假设:View是包含在ViewGroup当中的,则一些方法的执行顺序是:

      ViewGroup.dispatchTouchEvent ——》ViewGroup.onInterceptTouchEvent——》View.dispatchTouchEvent——》View.onTouchEvent

 

   一, 正常情况下:ViewGroup.dispatchTouchEvent事件中的一些执行方法:

 

            Event.Action_down:

            ViewGroup会捕获事件,如果disallowIntercept为true 或者(||)ViewGroup.onInterceptTouchEvent返回false,则遍历在当前坐标x,y下的子View;

            并将mMotionTarget=child,然后执行:View.dispatchTouchEvent。

 

           Event.Action_move:

          ViewGroup会捕获事件,如果disallowIntercept为true 或者(||)ViewGroup.onInterceptTouchEvent返回false,则执行child.DispatchTouchEvent。

否则,mMotionTargt=null  ,View(子控件)后面的Action_move,Action_UP 都无法捕获。

        

           Event.Action_up:

          ViewGroup会捕获事件,如果disallowIntercept为true 或者(||)ViewGroup.onIntercepttouchevent返回false,则执行child.dispatchTouchEvent。

否则,mMotionTarget=null,View(子控件)后面的Action_up无法捕获。

 

     二, ViewGroup可以通过ViewGroup.requestDisallowIntercept(boolean  aa)方法设置disallowIntercept的值。

               aa为true不允许拦截,为false允许拦截(并且在onIntercepttouchEvent方法中拦截成功才算正真的拦截即子控件(View)与Event有关的监听事件无效)。

              

    三,如果要精细到具体拦截那个事件的动作(Event.Action_down。。。。)

            可以复写ViewGroup的onInterceptTouchEvent方法

            

@Override  
02.    public boolean onInterceptTouchEvent(MotionEvent ev)  
03.    {  
04.        int action = ev.getAction();  
05.        switch (action)  
06.        {  
07.        case MotionEvent.ACTION_DOWN:  
08.            //如果你觉得需要拦截  
09.            return true ;   
10.        case MotionEvent.ACTION_MOVE:  
11.            //如果你觉得需要拦截  
12.            return true ;   
13.        case MotionEvent.ACTION_UP:  
14.            //如果你觉得需要拦截  
15.            return true ;   
16.        }  

注意的是如果,你再Action_Down时return true,则Action_Move,和Action_up都会被屏蔽。在Action_Move时,return true,Action_up会被屏蔽。因为在

ViewGroup.onInterceptTouchEvent方法返回true时,mMotionTarget会被置为null;

如果子View不想被父ViewGroup屏蔽,可一个在disPatchTouchEvent方法中加上:getParent().requestDisallowIntercept(true);

     四,ViewGroup也有onTouchEvent方法,这个方法只要子控件的clickable=true或者longClickable=true,则ViewGroup的ontouchEvent不会执行

 

                 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值