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

移动开发 Android 游戏开发
关于android双击事件 我相信大家都知道API中是有个方法的,但是必须在Activity中在能使用。对于到底用不用android双击事件API各有各的看法。在Activity中使用API,省时省力,别人写的东西,直接用就行了,不担心有BUG,但是代码写在activity中总感觉有些乱;自己写个onDoubleClick方法,自己写的东西,好控制,灵活性强,想放哪放哪,但是需要消耗点时间,检查BUG之类的。

在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. }   

 

责任编辑:闫佳明 来源: jizhuomi
相关推荐

2013-09-13 13:15:28

AndroidWebViewJavaScript

2013-05-21 14:15:23

Android游戏开发屏幕分辨率

2013-05-21 11:33:11

Android游戏开发按键中断事件

2013-05-20 16:53:55

Android游戏开发长按事件

2013-04-15 15:22:06

2013-05-21 10:42:48

Android游戏开发Bitmap位图旋转

2013-07-29 04:29:29

iOS开发iOS开发学习禁用UITabBarC

2013-05-21 11:26:49

Android游戏开发Sensor感应

2013-05-20 17:51:47

Android游戏开发SurfaceView

2009-09-10 18:18:42

C# Button

2015-02-03 14:45:55

android全局异常

2013-05-21 09:56:15

2013-05-21 13:55:51

Android游戏开发图像渐变特效

2013-05-20 17:48:20

2013-05-21 11:24:07

Android游戏开发Sensor重力感应

2011-06-02 10:09:18

2013-05-20 17:13:17

Android游戏开发CanvasPaint

2016-10-20 19:07:10

Javascript事件冒泡与捕获

2013-05-20 15:42:22

2013-05-20 17:33:44

Android游戏开发自定义View
点赞
收藏

51CTO技术栈公众号