許多開發者這樣寫:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
float centerY = size.y / 2f;
someImageView.setY(centerY); // 圖片沒跑到正中心?
問題在於 View.setY() 設定的是 **View 相對於父容器左上角的 Y 軸位移**,而非螢幕絕對座標。若父容器有 padding、margin、或本身未佔滿螢幕,視覺位置就會偏移。
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:id="@+id/centerImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/your_image" />
</FrameLayout>
// 在 onWindowFocusChanged 或 ViewTreeObserver 中執行
View root = findViewById(android.R.id.content).getRootView();
int screenH = root.getHeight();
int screenW = root.getWidth();
ImageView iv = findViewById(R.id.centerImage);
iv.post(() -> {
int iw = iv.getWidth();
int ih = iv.getHeight();
iv.setX((screenW - iw) / 2f);
iv.setY((screenH - ih) / 2f);
});
關鍵點:
• 使用 View.post(Runnable) 確保 View 已完成測量與佈局,getWidth/Height() 才有值。
• 座標基準是 **根視圖**,而非 Display。
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/centerImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:src="@drawable/your_image" />
</androidx.constraintlayout.widget.ConstraintLayout>
Display.getSize() 在 API 30+ 已棄用,建議改用:
WindowMetrics metrics = getWindowManager().getCurrentWindowMetrics();
WindowInsets insets = metrics.getWindowInsets();
Insets sysInsets = insets.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars());
int width = metrics.getBounds().width() - sysInsets.left - sysInsets.right;
int height = metrics.getBounds().height() - sysInsets.top - sysInsets.bottom;
「螢幕中心座標」≠「View 視覺置中」。**別直接拿螢幕尺寸去 setX/setY**,請用佈局層的 gravity、ConstraintLayout 或在 **根視圖座標系** 下計算置中位移。這才是 Android 佈局機制的正確打開方式。