Android自定义ViewAndroid实践

Android事件传递机制详解(嵌套自定义View示例)

2016-10-26  本文已影响282人  Mr云台

一、概述

自定义View如果嵌套了自定义View,可能简单写一个onTouchEvent处理事件已经不能解决你的需要。简单举个例子:

你自定义了一个容器View,简称为父View,在这里监听点击事件,做事情A,监听滑动做事情B

然后你又自定了一个View,放入该容器父View当中,也监听点击事件,当点击的时候做事件C,滑动时做事情D。

上面的事件A、C不是互斥的,意味着点击发生时,在子View中做一部分处理工作,然后父View中也做一部分处理工作。

事情B和D是互斥的,即父View发生滑动,则只做事情B

遇到这种情况,不理解清楚Android的事件传递机制是不行的。

二、理解Android的事件传递机制

一般的View都有dispatchTouchEvent,onTouchEvent方法,这个是从View中继承的,而具备容器功能的View如LinearLayout,额外多了onInterceptTouchEvent方法,这个是从ViewGroup父类中继承到的。

事件传递开始的顺序,一般如下:

1.点击屏幕,事件的传递从Activity的dispatchTouchEvent()方法开始。

2.在时间上,同一层级的分发顺序为

dispatchTouchEvent(分发) --- 
onInterceptTouchEvent(如果拦截) --- 
onTouchEvent(消费)

后两个方法的默认返回值都是false,ViewGroup的dispatchTouchEvent默认返回true,View的dispatchTouchEvent默认返回false,代码在下文中。


image

3.Android事件分发机制一般分为两个过程,先从上往下传递,再从下往上传递。

贴上别人总结的伪代码:

[java] view plain copy 在CODE上查看代码片派生到我的代码片
public boolean dispatchTouchEvent(MotionEvent ev) {    
     调用onInterceptTouchEvent检查是否拦截事件    
     if(没有拦截){    
         在ViewGroup中遍历查找目前是点击了哪个子视图    
         if(找到了){    
             调用该子视图的dispatchTouchEvent,递归下去    
         }else{    
             没找到,则将事件传给onTouchListener,没有Listener则传给onTouchEvent()    
             如果再listener或者onTouchEvent()中down事件返回了true,代表事件被消费,后续的move和up都被Listener或者onTouchEvent()处理,    
             如果down事件返回false,则后续的move,up事件将不会到这一层的Viewgroup,而直接在上一层视图被消费。    
         }     
     }else{    
         事件被拦截了,原本被点击的子视图将接收到一个ACTION_CANCEL事件,而down事件传给onTouchListener,没有Listener则传给onTouchEvent(),依然遵从上面的down和move,up事件的关系    
     }    
}

注意点

/**  
    * Implement this method to intercept all touch screen motion events.  This  
    * allows you to watch events as they are dispatched to your children, and  
    * take ownership of the current gesture at any point.  
    *  
    * <p>Using this function takes some care, as it has a fairly complicated  
    * interaction with {@link View#onTouchEvent(MotionEvent)  
    * View.onTouchEvent(MotionEvent)}, and using it requires implementing  
    * that method as well as this one in the correct way.  Events will be  
    * received in the following order:  
    *  
    * <ol>  
    * <li> You will receive the down event here.  
    * <li> The down event will be handled either by a child of this view  
    * group, or given to your own onTouchEvent() method to handle; this means  
    * you should implement onTouchEvent() to return true, so you will  
    * continue to see the rest of the gesture (instead of looking for  
    * a parent view to handle it).  Also, by returning true from  
    * onTouchEvent(), you will not receive any following  
    * events in onInterceptTouchEvent() and all touch processing must  
    * happen in onTouchEvent() like normal.  
    * <li> For as long as you return false from this function, each following  
    * event (up to and including the final up) will be delivered first here  
    * and then to the target's onTouchEvent().  
    * <li> If you return true from here, you will not receive any  
    * following events: the target view will receive the same event but  
    * with the action {@link MotionEvent#ACTION_CANCEL}, and all further  
    * events will be delivered to your onTouchEvent() method and no longer  
    * appear here.  
    * </ol>  
    *  
    * @param ev The motion event being dispatched down the hierarchy.  
    * @return Return true to steal motion events from the children and have  
    * them dispatched to this ViewGroup through onTouchEvent().  
    * The current target will receive an ACTION_CANCEL event, and no further  
    * messages will be delivered here.  
    */    
   public boolean onInterceptTouchEvent(MotionEvent ev) {    
       return false;    
   }
public boolean onTouchEvent(MotionEvent event) {  
     
     if(event.getAction()==MotionEvent.ACTION_DOWN) {  
         Log.i("test", "ACTION_DOWN发生");  
         return false;  
     }  
     //判断是向下滑动  
     if(event.getAction()==MotionEvent.ACTION_MOVE) {  
         Log.i("test", "ACTION_MOVE发生");  //这条语句是不会执行的  
     }  
      
     return super.onTouchEvent(event);  
 }

结果截图


image

三、实现第一点中提出的效果。

  1. 新建一个父类,代码如下
package com.example.administrator.myapplication;  
  
import android.content.Context;  
import android.util.AttributeSet;  
import android.util.Log;  
import android.view.MotionEvent;  
import android.widget.LinearLayout;  
  
/** 
 * Created by wangqinwei on 2016/10/20. 
 */  
  
public class MyFatherContainer extends LinearLayout {  
  
    public MyFatherContainer(Context context) {  
        super(context);  
    }  
  
    public MyFatherContainer(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        setBackgroundColor(getResources().getColor(R.color.colorPrimary));  
    }  
  
    public MyFatherContainer(Context context, AttributeSet attrs, int defStyleAttr) {  
        super(context, attrs, defStyleAttr);  
    }  
  
    @Override  
    public boolean dispatchTouchEvent(MotionEvent event) {  
        Log.i("WQW", "父View的dispatchTouchEvent被调用,默认返回:" + super.dispatchTouchEvent(event));  
  
        return super.dispatchTouchEvent(event);  
    }  
  
    @Override  
    public boolean onInterceptTouchEvent(MotionEvent ev) {  
        Log.i("WQW", "父View的onInterceptTouchEvent被调用,默认返回:" + super.onInterceptTouchEvent(ev));  
  
        if (ev.getAction() == MotionEvent.ACTION_MOVE) {  
            Log.i("test", "父View拦截滑动");  
            return true;  
        }  
  
        return super.onInterceptTouchEvent(ev);  
    }  
  
    @Override  
    public boolean onTouchEvent(MotionEvent event) {  
        Log.i("WQW", "父View的onTouchEvent被调用,默认返回:" + super.onTouchEvent(event));  
  
        if (event.getAction() == MotionEvent.ACTION_DOWN) {  
            Log.i("test", "父View发生点击,做事情A");  
            return true;   //这里一定要返回true,否则后续收不到滑动事件了  
        }  
  
        if (event.getAction() == MotionEvent.ACTION_MOVE) {  
            Log.i("test", "父View发生滑动,做事情B");  
        }  
        return super.onTouchEvent(event);  
    }  
}
  1. 新建一个子View
package com.example.administrator.myapplication;  
  
import android.content.Context;  
import android.util.AttributeSet;  
import android.util.Log;  
import android.view.MotionEvent;  
import android.view.View;  
  
public class MyChildView extends View {  
  
    public MyChildView(Context context) {  
        super(context);  
    }  
  
    public MyChildView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        setBackgroundColor(getResources().getColor(R.color.colorAccent));  
    }  
  
    public MyChildView(Context context, AttributeSet attrs, int defStyleAttr) {  
        super(context, attrs, defStyleAttr);  
    }  
  
    @Override  
    public boolean dispatchTouchEvent(MotionEvent event) {  
        Log.i("WQW", "子View的dispatchTouchEvent被调用,默认返回:" + super.dispatchTouchEvent(event));  
  
        return super.dispatchTouchEvent(event);  
    }  
  
    @Override  
    public boolean onTouchEvent(MotionEvent event) {  
        Log.i("WQW", "子View的onTouchEvent被调用,默认返回:" + super.onTouchEvent(event));  
  
        if (event.getAction() == MotionEvent.ACTION_DOWN) {  
            Log.i("test", "子View发生点击,做事情C");  
            return false;  //同时返回false,让事件返回给上层  
        }  
  
        if (event.getAction() == MotionEvent.ACTION_MOVE) { //这里其实父类拦截与否没有意义,因为ACTION_DOWN返回了false  
            Log.i("test", "子View发生滑动,做事情D");  
        }  
  
        return super.onTouchEvent(event);  
    }  
}
  1. 在Activity的布局文件中使用父View和子View
<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:id="@+id/activity_main"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:paddingBottom="@dimen/activity_vertical_margin"  
    android:paddingLeft="@dimen/activity_horizontal_margin"  
    android:paddingRight="@dimen/activity_horizontal_margin"  
    android:paddingTop="@dimen/activity_vertical_margin"  
    tools:context="com.example.administrator.myapplication.MainActivity"  
    >  
  
    <com.example.administrator.myapplication.MyFatherContainer  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:gravity="center"  
        >  
  
        <com.example.administrator.myapplication.MyChildView  
            android:layout_width="300dp"  
            android:layout_height="400dp"  
            />  
  
    </com.example.administrator.myapplication.MyFatherContainer>  
  
  
</RelativeLayout>

4.运行结果

image

其中红色的部分是子View,蓝色部分是父View。

在子View上点击,结果如下:


image

在子View上滑动,结果如下:


image

事件D并没有触发。

如果觉得我的文章帮到了你,请留个言呗~

参考的优秀博客: http://blog.csdn.net/chziroy/article/details/44401615

上一篇 下一篇

猜你喜欢

热点阅读