Android给控件添加触摸回调

来源:互联网 发布:java程序华氏温度转换 编辑:程序博客网 时间:2024/05/07 13:09

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        ……    }});
0 0
原创粉丝点击