简体   繁体   English

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

[英]Android: getting x, y coordinates of a view

I wrote the following code to find out the coordinates of touch point. 我编写了以下代码以找出接触点的坐标。

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;
            }

It turns out to be always returning the fixed value, 32.0 for each x coordinate and y coordinate. 原来总是返回固定值,每个x坐标和y坐标为32.0。

Instead of getting the x and y coordinates via view.getX() and view.getY() respectively inside the onTouch() method, the following worked. 下面的方法可以代替在onTouch()方法中分别通过view.getX()view.getY()获取x和y坐标。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM