Android-ViewGroup的事件机制

来源:互联网 发布:mac中文官网 编辑:程序博客网 时间:2024/06/05 14:30

     假设: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不会执行

 

                 

0 0
原创粉丝点击