UI执行顺序
了解一下UI的执行顺序,我们新建一个MyLinearLayout ,并继承LinearLayout,重写onMeasure(),onSizeChanged(),onLayout()方法
其中CenterLayout、ShadeView都是之前的自定义控件
布局结构如下
--
MyLinearLayout
----
CenterLayout
--------
ShadeView
<com.xx.shadeview.MyLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.xx.shadeview.CenterLayout xmlns:Shade="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.xx.shadeview.ShadeView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Shade:shade_color="#FF888888"
Shade:text="运动伙伴 就选酷跑"
Shade:text_color="#FF0000FF"
Shade:text_size="20" />
</com.xx.shadeview.CenterLayout>
</com.xx.shadeview.MyLinearLayout>
在MyLinearLayout ,CenterLayout ,ShadeView中打印日志

事件处理顺序
在MyLinearLayout、CenterView中重写以下三个方法
//分发
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d("事件处理顺序",this.toString()+" dispatchTouchEvent()");
return super.dispatchTouchEvent(ev);
}
//拦截
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.d("事件处理顺序",this.toString()+" onInterceptTouchEvent()");
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("事件处理顺序",this.toString()+" onTouchEvent() action:"+event.getAction());
return super.onTouchEvent(event);
}
在ShadeView,以及MainActivity中重写dispatchTouchEvent()、onTouchEvent()方法,打印日志
点击界面上的ShadeView,观察日志
正常事件处理顺序如下:
修改ShadeView的onTouchEvent,改为return true
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("事件处理顺序",this.toString()+" onTouchEvent() action:"+event.getAction());
//return super.onTouchEvent(event);
return true;
}
再次点击界面上的ShadeView,观察日志
当ShadeView的onTouchEvent()返回true后,容器的onTouchEvent()就不执行了。而且点击事件分为了按下:0、抬起:1、移动:2。当进行移动时,事件会分发多次
当return super.onTouchEvent(event);时,只有按下
现在将ShadeView的onTouchEvent改为return super.onTouchEvent(event);
然后修改CenterLayout中的onInterceptTouchEvent()方法返回值为true
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.d("事件处理顺序",this.toString()+" onInterceptTouchEvent()");
//return super.onInterceptTouchEvent(ev);
return true;
}
这样会导致其子控件ShadeView的onTouchEvent()执行不到,因为进行了拦截
观察日志

总结