Android 如何获得x&;视图的Y坐标

Android 如何获得x&;视图的Y坐标,android,android-layout,android-constraintlayout,Android,Android Layout,Android Constraintlayout,我已经在我的布局中放置了一个图像视图,现在我需要知道它的x&y坐标,以便在它上面动态地绘制一些东西 我尝试了imageView.getTop()&imageView.getY()但它们都返回“0”,但图像不是从“0”开始的,从开始到结束有一些边距,从顶部到结束有很多边距 是否有其他方法获取此信息。尝试使用imageView.getLocationOnScreen(int[])获取相对于其父/屏幕的视图的X和Y: int[] positions = new int[2]; imageView.g

我已经在我的布局中放置了一个图像视图,现在我需要知道它的x&y坐标,以便在它上面动态地绘制一些东西

我尝试了
imageView.getTop()
&
imageView.getY()
但它们都返回“0”,但图像不是从“0”开始的,从开始到结束有一些边距,从顶部到结束有很多边距


是否有其他方法获取此信息。

尝试使用imageView.getLocationOnScreen(int[])获取相对于其父/屏幕的视图的X和Y:

int[] positions = new int[2];
imageView.getLocationOnScreen(positions);
int x = positions[0];
int y = positions[1];

要确保视图有机会更新,请在使用view.post计算视图的新布局后运行位置请求:

view.post {
    val point = IntArray(2)
    view.getLocationOnScreen(point)
    val (x, y) = point
}
值不应再为0,但我对华为设备有过不好的体验。获取x和y坐标的另一种方法是使用viewTreeObserver

view.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                view.viewTreeObserver.removeOnGlobalLayoutListener(this)      
                val point = IntArray(2)
                view.getLocationOnScreen(point)
                val (x, y) = point
            }
});
可能您在这种方法中遇到了一些视觉故障

也许这有助于: