Android游戏开发之十九:屏幕双击事件的捕获

Android游戏开发中,我们可能经常要像PC操作一样在屏幕上双击。对于屏幕双击操作,Android 1.6版本以前并没有提供完善的手势识别类,Android 1.5的SDK中提供了android.view.GestureDetector.OnDoubleTapListener,但经测试无法正常工作,不知是何原因。最终我们的解决方案如下面的代码:

 
 
  1. public class TouchLayout extends RelativeLayout {    
  2.     public Handler doubleTapHandler = null;    
  3.     protected long lastDown = -1;    
  4.     public final static long DOUBLE_TIME = 500;    
  5.  public TouchLayout(Context context) {    
  6.        super(context);    
  7.     }    
  8.     public TouchLayout(Context context, AttributeSet attrs) {    
  9.        super(context, attrs);    
  10.     }    
  11.     public TouchLayout(Context context, AttributeSet attrs, int defStyle) {    
  12.        super(context, attrs, defStyle);    
  13.     }    
  14.     public boolean onTouchEvent(MotionEvent event) {    
  15.          this.handleEvent(event);    
  16.          if (event.getAction() == MotionEvent.ACTION_DOWN) {    
  17.             long nowDown = System.currentTimeMillis();    
  18.             if (nowDown - lastDown < DOUBLE_TIME)    
  19.             {    
  20.                   if (doubleTapHandler != null)    
  21.                      doubleTapHandler.sendEmptyMessage(-1);    
  22.             } else {    
  23.                lastDown = nowDown;    
  24.             }    
  25.          }    
  26.          return true;    
  27.       }    
  28.     protected void handleEvent(MotionEvent event) {    
  29.         switch (event.getAction()) {    
  30.         case MotionEvent.ACTION_DOWN:    
  31.          //Do sth 这里处理即可    
  32.            break;    
  33.         case MotionEvent.ACTION_UP:    
  34.            //Do sth    
  35.            break;    
  36.         }    
  37.      }    
  38. }   

 

THE END