测试方式:重写LinearLayout和Button如下:
package com.gitonway.lee.niftymodaldialogeffects;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.LinearLayout;
public class MyLinearLayout extends LinearLayout {
public MyLinearLayout(Context context) {
super(context);
}
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.v("EVENTTOUCHTEST", "MyLinearLayout onTouchEvent Action = " + event.getAction());
return true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.d("EVENTTOUCHTEST", "MyLinearLayout onInterceptTouchEvent Action = " + ev.getAction());
return false;
}
}
package com.gitonway.lee.niftymodaldialogeffects;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Button;
public class MyButton extends Button {
public MyButton(Context context) {
super(context);
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i("EVENTTOUCHTEST", "MyButton onTouchEvent Action = " + event.getAction());
return super.onTouchEvent(event);
}
}
测试是mylinearlayout包含mybutton,注:只有viewgroup才有onInterceptTouchEvent方法
1、onInterceptTouchEvent返回true,mylinearlayout的onTouchEvent会消费action,mybutton的onTouchEvent不会响应
2、onInterceptTouchEvent返回false,onTouchEvent返回true,button的onTouchEvent返回false,mybutton先消费
onTouchEvent,然后mylinearlayout消费onTouchEvent
3、onInterceptTouchEvent返回false,onTouchEvent返回true,button的onTouchEvent返回true,mybutton了消费
onTouchEvent,该action不会再回传给mylinearlayout
总结:onInterceptTouchEvent返回true,则action不再传给子view
当onInterceptTouchEvent返回false的时候,如果view的onTouchEvent返回false则表示该view不关注(但会响应)
该action,会把action传给其父view,如果view的onTouchEvent返回true,则该action不再回传给父view
底层View的getParent().requestDisallowInterceptTouchEvent(true)
对于底层的View来说,有一种方法可以阻止父层的View截获touch事件,就是调用getParent().requestDisallowInterceptTouchEvent(true);方法。一旦底层View收到touch的action后调用这个方法那么父层View就不会再调用onInterceptTouchEvent了,也无法截获以后的action