我有自定义视图中检测长按的问题.
这是与此问题相关的代码
final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() { public void onLongPress(MotionEvent e) { Log.e("dbg_msg","onLongPress"); } }); public boolean onTouchEvent(MotionEvent event) { return gestureDetector.onTouchEvent(event); };
此代码可以长时间检测每一个(短)点击.
当我将此代码放在继承自Activity的类中时,它可以工作.
那么为什么它不能在自定义视图中工作?
解决方法
所有这些代码都在你的自定义视图类中:
public static int LONG_PRESS_TIME = 500; // Time in miliseconds final Handler _handler = new Handler(); Runnable _longPressed = new Runnable() { public void run() { Log.i("info","LongPress"); } }; @Override public boolean onTouchEvent(MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_DOWN: _handler.postDelayed(_longPressed,LONG_PRESS_TIME); break; case MotionEvent.ACTION_MOVE: _handler.removeCallbacks(_longPressed); break; case MotionEvent.ACTION_UP: _handler.removeCallbacks(_longPressed); break; } return true; }