解决android平台Activity 双击事件监听事件派发问题
2013-01-15 15:42:50 来源:开发学院核心提示:public class DoubleClick{private int clickCount;private long firstClickTime;private int CLICK_DELAY = 300;private final static int MOVE_OFFSET = 20;private floa
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; // 判断是否是移动 if (yMoved || xMoved) { clickCount = 0; firstClickTime = 0; } } } }
使用实例:
private DoubleClick doubleClick; //当需要使用双击事件监听,调用此方法即可。 protected void enableDClickReturn(){ doubleClick = new DoubleClick(new DoubleClick.OnDoubleClickListener() { @Override public void onDoubleClick() { //这里我的项目需要的功能是双击返回上一级Activity finish(); } }); } @Override public boolean dispatchTouchEvent(MotionEvent event) { if(doubleClick == null) { return super.dispatchTouchEvent(event); }else{ doubleClick.dispatchTouchEvent(event); } return super.dispatchTouchEvent(event); }
- ››Android 当修改一些代码时,使用什么编译命令可以最...
- ››Android 如何添加一个apk使模拟器和真机都编译进去...
- ››Android 修改Camera拍照的默认保存路径
- ››Android 如何修改默认输入法
- ››android开发中finish()和System.exit(0)的区别
- ››Android手势识别简单封装类
- ››android中查看项目数字证书的两种方法
- ››Android中获取IMEI码的办法
- ››android 相机报错 setParameters failed
- ››Android重启运用程序的代码
- ››Android为ListView的Item设置不同的布局
- ››android bitmap与base64字符串的互相转换
更多精彩
赞助商链接