有时候我们需要针对按钮的长按事件进行响应,这个Android已经有onLongClick事件了。但也有需求就是在手指抬起的时候也有回调,这里我简单封装了一下,免得在Activity类中代码过于复杂。
/**
* Created by Xiaoxuan948 on 2015/11/2.
* Desc:包含长按事件(区别于长击事件)
* 用法示例:View.setOnTouchListener(new ExpandGestureDetectorListener(getCurrentActivity(), new onLongTouchListener() ...);
*/
public class ExpandGestureDetectorListener implements View.OnTouchListener {
private static final UnifyLog lg = UnifyLogFactory.getLogger(ExpandGestureDetectorListener.class.getSimpleName());
private GestureDetector gestureDetector;
private boolean isOnLongTouch;
private View touchView;
private onLongTouchListener onLongTouchListener;
private onClickListener onClickListener;
public ExpandGestureDetectorListener(Context context, onLongTouchListener _onLongTouchListener) {
this(context, _onLongTouchListener, null);
}
public ExpandGestureDetectorListener(Context context, final onClickListener _onClickListener) {
this(context, null, _onClickListener);
}
private ExpandGestureDetectorListener(Context context, onLongTouchListener _onLongTouchListener, final onClickListener _onClickListener) {
isOnLongTouch = false;
this.onLongTouchListener = _onLongTouchListener;
this.onClickListener = _onClickListener;
this.gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
// @Override
// public boolean onSingleTapUp(MotionEvent e) {
// L.e(TAG, "onSingleTapUp");
// if (onClickListener != null) {
// onClickListener.onClick();
// }
// return super.onSingleTapUp(e);
// }
@Override
public void onLongPress(MotionEvent e) {
lg.e("onLongPress:start");
isOnLongTouch = true;
if (onLongTouchListener != null) {
onLongTouchListener.onLongTouchStart(touchView);
}
super.onLongPress(e);
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
lg.e("onScroll");
return super.onScroll(e1, e2, distanceX, distanceY);
}
});
}
@Override
public boolean onTouch(View view, MotionEvent event) {
this.touchView = view;
if (!view.isClickable()) {
//不加这句判断,则始终走onLongPress,不执行onSingleTapUp方法
throw new IllegalAccessError("Current View could`t answer Click Event,Please setClickable(true) or setonClickListener(...)");
}
if (gestureDetector != null) {
boolean result = gestureDetector.onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
if (isOnLongTouch) {
lg.e("onLongPress:end");
isOnLongTouch = false;//还原长按标识符
if (onLongTouchListener != null) {
onLongTouchListener.onLongTouchEnd(touchView);
}
}
}
return result;
}
return false;
}
public interface onLongTouchListener {
void onLongTouchStart(View view);
void onLongTouchEnd(View view);
}
public interface onClickListener {
void onClick();
}
}
注:自己有强迫症了开始,一拿到代码就想着怎么封装~~