要拿到某個 View 在螢幕上的位置,用 getLocationOnScreen() 就對了。但這裡藏著一個幾乎每個人都會踩到的坑:時機。
如果你在 onCreate() 裡急著印出座標,拿到的會是全 0。原因是那個時候 UI 元件還沒真正被量測與配置完成,位置資訊自然還是空的。正確做法是把讀取動作延後到使用者點擊按鈕時,或註冊 ViewTreeObserver 的版面回呼。
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
/**
* 在 onCreate() 中輸出控件位置會全為 0,
* 必須等 UI 元件都載入完成後才拿得到真正的數值。
*/
public class GetLocationData extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/* 點擊按鈕才讀取座標 */
public void click(View v){
View view = findViewById(R.id.button2);
// 陣列長度必須為 2
int[] locations = new int[2];
view.getLocationOnScreen(locations);
int x = locations[0]; // 橫座標
int y = locations[1]; // 縱座標
Log.i("System.out", "x:" + x + "y:" + y);
}
}
getLocationOnScreen() 回報的是相對整面螢幕(含狀態列)的絕對位置,而 getLocationInWindow() 回報的是相對目前視窗左上角的位置,在有多視窗或懸浮窗的情境下兩者會不一樣。若只是想知道 View 在父容器中的偏移,用 getLeft()/getTop() 會更單純。