首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 取得螢幕中心座標的正確姿勢

     編輯:程式設計綜合問答

常見誤區:以為算出座標就能直接用

許多開發者這樣寫:

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、或本身未佔滿螢幕,視覺位置就會偏移。

正確做法:根據佈局容器置中

方案一:XML 佈局用 gravity(最簡單)

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

方案二:程式碼動態置中(需在 layout 完成後)

// 在 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。

方案三:ConstraintLayout 置中(現代標準)

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

補充:取得螢幕尺寸的現代 API

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 佈局機制的正確打開方式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved