Android给控件添加触摸回调

效果图

Android给控件添加触摸回调-LMLPHP

实现方法

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
……
}
});
05-02 04:25