补充知识点:LinearLayout extends ViewGroup
extends View
1、Android事件分发是先传递到ViewGroup,再由ViewGroup传递到View的。
2、在ViewGroup中可以通过onInterceptTouchEvent方法对事件传递进行拦截,onInterceptTouchEvent方法返回true代表不允许事件继续向子View传递,返回false代表不对事件进行拦截,默认返回false。
3、子View中如果将传递的事件消费掉,ViewGroup中将无法接收到任何事件。
1、自定义布局控件(ViewGroup事件)
public class CustomLayout extends LinearLayout {
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) { //intercept 拦截
return true; //自己消费,touch事件拦截,子事件无法响应
return false; //自己不消费,子事件响应拦截事件
}
public CustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
2、布局文件
<com.example.touchevent.CustomLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/custom_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.test.TouchMainActivity" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="btn1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="btn2" />
</com.example.touchevent.CustomLayout>
3、事件响应
CustomLayout cl=(CustomLayout) findViewById(R.id.custom_layout);
cl.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TAG, "cl响应点击");
return false; //自己消费点击事件,不再分发给子View
}
});
Button btn1=(Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "btnl响应点击");
}
});
Button btn2=(Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "btn2响应点击");
}
});
btn1.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("TAG", "TouchEvent触发"+event.getAction());
return true; //自己是否消费掉事件 true:自己消费不下发 false:不消费下发到子控件
}
});