MotionEvent android使用

在Android的View中,手势检测用于辅助检测用户单击、滑动、长按、双击等行为。我们这篇文章主要介绍如何使用它:

一、GestureDetector.OnGestureListener

1、我们可以通过这个接口监听一些手势

代码如下:

public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {

    private static final String TAG = "MainActivity";
    private GestureDetector gestureDetector;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gestureDetector = new GestureDetector(this);

    }

    public MainActivity() {
        super();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        return gestureDetector.onTouchEvent(event);
    }
    
    

    @Override
    public boolean onDown(MotionEvent e) {

        Log.i(TAG, "onDown: 点击了");
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        Log.i(TAG, "onSingleTapUp: 点击了");
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        Log.i(TAG, "onScroll: 点击了");
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        Log.i(TAG, "onFling: 点击了");
        return false;
    }
}

如果我们是单点之后可以看到日志:

 滑动的日志:

 长点击:

 都可以检测到。

2、滑动的速度检测

在onTouchEvent(这个是属于View的,你也可以在GestureDetector.OnGestureListener接口中写)中我们可以加入速度检测的代码:

        VelocityTracker obtain = VelocityTracker.obtain();
        obtain.addMovement(event);

        obtain.computeCurrentVelocity(100);

        int xVelocity = (int) obtain.getXVelocity();
        int yVelocity = (int) obtain.getYVelocity();
        obtain.clear();
        obtain.recycle();
        Log.i(TAG, "onTouchEvent:x速度: "+xVelocity);
        Log.i(TAG, "onTouchEvent:y速度: "+yVelocity);

这样手势滑动的时候就可以检测到速度,这里我设置的时间是100ms。速度=(终点位置-起点位置)/时间段

 其中上下左右的滑动不同,速度值为正负;

原文地址:https://www.cnblogs.com/hequnwang/p/14284234.html