Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 佈局居中的三種實現方式

編輯:關於 Android 程式設計

「讓一個 View 在父容器裡居中」看似簡單,但 Android 提供了三個不同的屬性來做這件事,適用範圍各異。用錯了會發現屬性完全不生效,這是初學階段常見的困惑點。

一、android:layout_gravity

用於指定當前組件在父容器中的位置。使用前提是父佈局必須是 LinearLayout 或其後裔——這是最容易踩的坑,寫在 RelativeLayout 的子 View 上不會有任何效果。

可能的取值包括:

  • top / bottom
  • left / right / start / end
  • center_vertical / center_horizontal / center
  • fill_vertical / fill_horizontal / fill
  • clip_vertical / clip_horizontal

其中與居中相關的是 center(水平垂直都居中)、center_horizontal、center_vertical。

需要注意的是,在 LinearLayout 的單一方向上,layout_gravity 只對交叉軸有效。比如豎向 LinearLayout 中,layout_gravity="left" 起作用,而 layout_gravity="top" 則被忽略——因為主軸位置由排列順序決定。想讓子 View 在主軸方向居中,需要配合 layout_weight 或改用其他佈局。

完整說明可參考 LinearLayout.LayoutParams 文檔。

二、android:gravity

用於指定View 的子組件在 View 中的位置,或者 View 內容在自身範圍內的對齊方式。它適用於所有的 View 和佈局,通用性最強。

與居中相關的取值:

  • center
  • center_horizontal
  • center_vertical

區別在於作用對象不同:

  • 設在佈局上(如 LinearLayout),其子組件會居中排列;
  • 設在 View 上(如 TextView),其內容會居中,例如文字居中顯示。

重力值支持用 | 組合,例如 android:gravity="bottom|right" 表示內容靠右下角對齊。

完整枚舉可參考 Gravity 類文檔。

三、android:layout_centerInParent

這是 RelativeLayout 專屬的佈局屬性。當一個組件的直接父佈局是 RelativeLayout 時,寫 android:layout_centerInParent="true" 即可讓它居中,取值只有 true 與 false。

同族的還有兩個:

  • android:layout_centerHorizontal="true":水平居中
  • android:layout_centerVertical="true":垂直居中

三個屬性可以組合使用,例如同時設 layout_centerHorizontal 與 layout_centerVertical 等價於 layout_centerInParent。

詳見 RelativeLayout.LayoutParams 文檔。

選型速查

  • 父佈局是 LinearLayout,要讓子 View居中 → android:layout_gravity(注意交叉軸限制)
  • 父佈局是 LinearLayout,要讓子 View 的內容居中 → android:gravity
  • 父佈局是 RelativeLayout → android:layout_centerInParent 系列
  • 父佈局是 FrameLayout → 用 android:layout_gravity(FrameLayout 支持兩個方向)
  • ConstraintLayout → 直接用 layout_constraintLeft_toLeftOf 等約束,居中靠對稱約束實現

記住一條判斷依據:gravity 管「裡面的東西怎麼擺」,layout_gravity 管「我自己在爸爸家的位置」。名字裡的 layout_ 前綴就是「我在父佈局中的佈局參數」這一含義的標記。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved