自定義View的事件
在Android系統中需要自定義View的事件,它根據根據鼠標拖動,長按,點擊等事件進行處理。
--使用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 down
void onShowPress(MotionEvent e);//Touch了還沒有滑動
boolean onSingleTapUp(MotionEvent e);//like onClick->onKeyUp
boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY);//scroll
void onLongPress(MotionEvent e);//long press
boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);//快速拖動
顧名思義可以想見這些方法的用途。
在實際使用過程中發現有一個問題:
當上下拖動的過程中向左右拖然後鬆開鼠標會不響應onTouchEvent的ACTION_UP事件,
所以要根據情況在onScroll中對distanceX和distanceY同時進行判斷。
--使用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 down
void onShowPress(MotionEvent e);//Touch了還沒有滑動
boolean onSingleTapUp(MotionEvent e);//like onClick->onKeyUp
boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY);//scroll
void onLongPress(MotionEvent e);//long press
boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);//快速拖動
顧名思義可以想見這些方法的用途。
在實際使用過程中發現有一個問題:
當上下拖動的過程中向左右拖然後鬆開鼠標會不響應onTouchEvent的ACTION_UP事件,
所以要根據情況在onScroll中對distanceX和distanceY同時進行判斷。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.