如果父类的onInterceptTouchEvent拦截了事件,子类可以通过requestDisallowInterceptTouchEvent(true)方法让父类不拦截该事件但是需要在子类监听onTouchListener监听到Action_Down事件之后再设置。并且父类不能拦截Action_Down事件。
因为ViewGroup在接收到Action_Down事件后,重置了请求不允许拦截的值
子类接收到Action_Down事件之后可以请求父类不拦截点击事件。栗子如下:
/**
* ViewGroup
*/
public class MyViewGroup extends LinearLayout{
public MyViewGroup(Context context) {
super(context);
}
public MyViewGroup(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyViewGroup(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.i("嘻嘻","dispatchTouchEvent "+ev.getAction());
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.i("嘻嘻","onInterceptTouchEvent "+ev.getAction());
if(ev.getAction()==MotionEvent.ACTION_DOWN){
return false;
}
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i("嘻嘻","onTouchEvent "+event.getAction());
return false;
}
}
<?xml version="1.0" encoding="utf-8"?>
<com.alipay.sdk.pay.demo.MyViewGroup xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.alipay.sdk.pay.demo.TestActivity">
<LinearLayout
android:id="@+id/root_view"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#f00"
android:clickable="true"
android:orientation="vertical"/>
</com.alipay.sdk.pay.demo.MyViewGroup>
public class TestActivity extends Activity {
LinearLayout rootView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
rootView = findViewById(R.id.root_view);
rootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("嘻嘻", "哈哈哈 rootView setOnClickListener ");
}
});
rootView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i("嘻嘻", "rootView onTouch " + event.getAction());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
rootView.requestDisallowInterceptTouchEvent(true);
break;
}
return false;
}
});
}
}