WEB开发网
开发学院手机开发Android 开发 解决android平台Activity 双击事件监听事件派发问... 阅读

解决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);
	} 

Tags:解决 android 平台

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接