Android给控件添加触摸回调

Android给控件添加触摸回调

脑补一个场景,一个页面点击某个按钮会弹出PopupWindow,然后点击PopupWindow以外的任意位置关闭

效果图

P1

实现方法

可以在布局的最外层容器监听触摸事件,下面部分以RelativeLayout为例

1. 重写RelativeLayout

package com.bitmain.btccom.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

import com.bitmain.btccom.interfaces.BitmainOnTouchListener;

/**
 * Created by kongqw on 2016/1/29.
 */
public class BitmainRelativeLayout extends RelativeLayout {

    private BitmainOnTouchListener mOnTouchListener;

    public BitmainRelativeLayout(Context context) {
        super(context);
    }

    public BitmainRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BitmainRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    public void setOnTouchHandler(BitmainOnTouchListener onTouchListener) {
        mOnTouchListener = onTouchListener;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // 通知父控件是否将事件传递下来
        // getParent().requestDisallowInterceptTouchEvent(true);
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (null != mOnTouchListener)
                    mOnTouchListener.onTouch();
        }
        return super.dispatchTouchEvent(ev);
    }
}

2. 触摸回调的接口

package com.bitmain.btccom.interfaces;

/**
 * Created by kongqw on 2016/1/29.
 */
public interface BitmainOnTouchListener {
    public void onTouch();
}

3. 使用

// 监听页面被触摸
BitmainRelativeLayout relativeLayout = (BitmainRelativeLayout) findViewById(R.id.relativeLayout);
relativeLayout.setOnTouchHandler(new BitmainOnTouchListener() {
    @Override
    public void onTouch() {
        // TODO 监听到控件被触摸 关掉PopupWindow
        ……
    }
});

转载于:https://www.cnblogs.com/sesexxoo/p/6190448.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值