参考地址:http://blog.csdn.net/reakingf/article/details/52029575
上代码:
首先先创建一个Layout,这个Layout是ViewGroup类型,我这里就用个LinearLayout,因为LinearLayout也是继承自ViewGroup。
ViewGroup在事件分发中主要有三个方法:dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent:
1.dispatchTouchEvent:该方法主要是做ViewGroup的事件分发,一般来说不进行处理。
2.onInterceptTouchEvent: 用于事件的拦截向下分发,只存在ViewGroup中。
3.onTouchEvent:该方法主要是触摸事件的处理。
然后创建一个View,这个Layout是View类型,我这里就继承TextView作为实例,因为TextView也是继承自View。
View在事件分发中主要有两个个方法:dispatchTouchEvent、onTouchEvent:
public class MyTextView extends TextView {
private String tag = "TestViewDispatchActivity";
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyTextView(Context context) {
super(context);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.d(tag, "dispatchTouchEvent---->MyTextView");
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(tag, "onTouchEvent---->MyTextView");
return super.onTouchEvent(event);
}
}
测试准备好的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.testdemo.viewdispatchtouch.MyViewGroupLayout
android:id="@+id/myLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.testdemo.viewdispatchtouch.MyTextView
android:id="@+id/myTextView"
android:layout_width="match_parent"
android:textSize="18sp"
android:textColor="#000000"
android:layout_height="wrap_content"
android:text="click" />
</com.example.testdemo.viewdispatchtouch.MyViewGroupLayout>
</LinearLayout>
测试Activity
public class TestViewDispatchActivity extends Activity{
private String tag = TestViewDispatchActivity.class.getSimpleName();
private MyViewGroupLayout myLayout;
private MyTextView myTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_viewdispatch);
initView();
}
private void initView(){
myLayout = (MyViewGroupLayout)findViewById(R.id.myLayout);
myTextView = (MyTextView)findViewById(R.id.myTextView);
}
}
如下图:运行结果可以看出执行顺序
点击click后会先执行viewgroup中的dispatchTouchEvent、onInterceptTouchEvent;
然后会进入到TextView也就是view中执行view的dispatchTouchEvent、onTouchEvent,
由于TextView的onTouchEvent不做处理返回false,所以将事件继续往上一级反馈,将事件继续传递给viewgroup。