Android:获取视图的x,y坐标

时间:2016-12-12 11:57:18

标签: android

我写了下面的代码来找出触点的坐标。

view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                float val = view.getAlpha();
                float xVal = view.getX();
                float yVal = view.getY();
                String message = "Screen height: " + height + ", width: " + width + "\n" +
                        "Alpha Value: " + val + ", x Coordinate: " + xVal + ", y Coordinate: " + yVal;
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                return false;
            }

事实证明,每个x坐标和y坐标总是返回固定值32.0。

1 个答案:

答案 0 :(得分:1)

不是通过view.getX()方法分别通过view.getY()onTouch()获取x和y坐标,而是以下方法。

float xVal = motionEvent.getX(); float yVal = motionEvent.getY();