事件分发机制(二)

补充知识点: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:不消费下发到子控件
            }
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值