How to get the Touch position in android?

我需要在android中获取触摸开始位置(X,Y),触摸移动位置和触摸屏幕的结束位置。


@Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int)event.getX();
    int y = (int)event.getY();
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
    }
return false;
}

这三种情况可以让你对不同类型的事件作出反应,在这个例子中,轻敲或拖动或再次举起手指。


@Override
    public boolean onTouch(View v, MotionEvent event) {
       float x = event.getX();
       float y = event.getY();
       return true;
    }

Supplemental answer

Given an OnTouchListener

private View.OnTouchListener handleTouch = new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.i("TAG", "touched down");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.i("TAG", "moving: (" + x + ", " + y + ")");
                break;
            case MotionEvent.ACTION_UP:
                Log.i("TAG", "touched up");
                break;
        }

        return true;
    }
};

set on some view:

myView.setOnTouchListener(handleTouch);

This gives you the touch event coordinates relative to the view that has the touch listener assigned to it. The top left corner of the view is (0, 0) . If you move your finger above the view, then y will be negative. If you move your finger left of the view, then x will be negative.

int x = (int)event.getX();
int y = (int)event.getY();

If you want the coordinates relative to the top left corner of the device screen, then use the raw values.

int x = (int)event.getRawX();
int y = (int)event.getRawY();

Related

  • How are Android touch events delivered?
  • 链接地址: http://www.djcxy.com/p/91212.html

    上一篇: 将Fling手势添加到图像视图

    下一篇: 如何获得在Android的触摸位置?