首页 / 操作系统 / Linux / Android系统中捕获鼠标事件
在Android系统中需要根据根据鼠标拖动,长按,点击等事件进行处理。--使用android.view.GestureDetector这个接口首先将自己的view继承此接口:public class MyView extends View implements OnClickListener,GestureDetector.OnGestureListener在view中添加GestureDetector的对象并初始化:private GestureDetector mGestureDetector;init() { mGestureDetector = new GestureDetector(getContext(), this);}之后重写view的onTouchEvent方法:public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break; case MotionEvent.ACTION_UP:
break;
}
return mGestureDetector.onTouchEvent(event);
}正常情况下以上步骤即可以将鼠标事件捕捉,并使用OnGestureListener接口方法去处理。boolean onDown(MotionEvent e);//mouse downvoid onShowPress(MotionEvent e);//Touch了还没有滑动boolean onSingleTapUp(MotionEvent e);//like onClick->onKeyUpboolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY);//scrollvoid onLongPress(MotionEvent e);//long pressboolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);//快速拖动顾名思义可以想见这些方法的用途。在实际使用过程中发现有一个问题:当上下拖动的过程中向左右拖然后松开鼠标会不响应onTouchEvent的ACTION_UP事件,所以要根据情况在onScroll中对distanceX和distanceY同时进行判断。