其中Layout里的onInterceptTouchEvent默认返回值是false,这样touch事件会传递到View控件,Layout里的onTouch默认返回值是false, View里的onTouch默认返回值是true,当我们手指点击屏幕时候,先调用ACTION_DOWN事件,当onTouch里返回值是true的时候,onTouch回继续调用ACTION_UP事件,如果onTouch里返回值是false,那么onTouch只会调用ACTION_DOWN而不调用ACTION_UP.
xml:
<?xml version="1.0" encoding="utf-8"?> <com.tutor.touch.MyLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <com.tutor.touch.MyView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </com.tutor.touch.MyLayout>
MyLayout.java
public class MyLayout extends FrameLayout { public MyLayout(Context context){ super(context); } public MyLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { Log.e(TouchDemoActivity.TAG, "MyLayout onInterceptTouchEvent."); Log.e(TouchDemoActivity.TAG,"MyLayout onInterceptTouchEvent default return " + super.onInterceptTouchEvent(ev)); return super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent event) { Log.e(TouchDemoActivity.TAG, "MyLayout onTouchEvent."); Log.e(TouchDemoActivity.TAG,"MyLayout onTouchEvent default return " + super.onTouchEvent(event)); return super.onTouchEvent(event); } }
MyView .java
public class MyView extends Button { public MyView(Context context){ super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onTouchEvent(MotionEvent event) { Log.e(TouchDemoActivity.TAG, "MyView onTouchEvent."); Log.e(TouchDemoActivity.TAG,"MyView onTouchEvent default return " + super.onTouchEvent(event)); return super.onTouchEvent(event); }
点击红色区域,触发了MyView里的onTouch事件
点击绿色区域,则触发了MyLayout里的onTouch事件,查看logcat,如下图:
上面俩个截图都是用系统默认值,可以得出结论:onInterceptTouchEvent默认返回值是false,MyLayout里onTouchEvent默认返回值是false,所以只消费了ACTION_DOWN事件,MyView里onTouch默认返回值是true,调用了俩次:ACTION_DOW,ACTION_UP。
时间: 2024-10-08 16:36:02