[英]How to get the x & Y coordinates of a view
嘗試使用 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
}
});
使用這種方法,您可能會遇到一些視覺故障
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.