`

自定义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同时进行判断。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics