使用手势识别类GestureDetector可以用标准的SDK类实现双击监听,但存在一个局限性:由于GD是在OnTouchEvent方法中拦截事件进行处理,而Android事件派发流程,使得如果Activity内部的View会消耗点击事件,GD就无法接受到点击事件了。
为此,本人实现一个可以完美监听Activity事件的工具类:DoubleClick.
类的全部源码:
[java]
public class DoubleClick{
private int clickCount;
private long firstClickTime;
private int CLICK_DELAY = 300;
private final static int MOVE_OFFSET = 20;
private float mLastMotionY;
private float mLastMotionX;
private Timer cleanClickTimer = new Timer();
private OnDoubleClickListener listener;
public DoubleClick(OnDoubleClickListener l){
listener = l;
}
public interface OnDoubleClickListener{
void onDoubleClick();
}
public void dispatchTouchEvent(MotionEvent event){
final float y = event.getY();
final float x = event.getX();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mLastMotionY = y;
mLastMotionX = x;
clickCount++;
if(clickCount == 1){
firstClickTime = System.currentTimeMillis();
//超过监听时间50MS还没有再次点击,则将点击次数,点击事件清零。
cleanClickTimer.schedule(new TimerTask() {
@Override
public void run() {
clickCount = 0;
firstClickTime = 0;
}
}, CLICK_DELAY+50);
}else if(clickCount == 2){
long secondClickTime = System.currentTimeMillis();
if (secondClickTime - firstClickTime <= CLICK_DELAY) {
listener.onDoubleClick();
}
clickCount = 0;
firstClickTime = 0;
}
}
if(event.getAction() == MotionEvent.ACTION_MOVE){
final int yDiff = (int) Math.abs(y - mLastMotionY);
final int xDiff = (int) Math.abs(x - mLastMotionX);
boolean yMoved = yDiff > MOVE_OFFSET;
boolean xMoved = xDiff > MOVE_OFFSET;
// 判断是否是移动
更多关注: