萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 五大經典佈局 (Layout) 全解析:LinearLayout、RelativeLayout、FrameLayout、TableLayout、AbsoluteLayout

概覽對照表

佈局特點適用場景備註
LinearLayout線性垂直/水平排列,支援 weight 分配剩餘空間表單、列表項、工具列、簡單堆疊最常用、巢狀過深影響效能
RelativeLayout相對定位 (相對父容器或兄弟元素)複雜對齊、重疊、居中、對齊基線扁平化佈局利器,但複雜依賴難維護
FrameLayout單幀疊加,子元素堆疊左上角Fragment 容器、覆蓋層、圖片疊加、動畫切換最簡單、單一子元素最佳
TableLayout表格行列 (),類 HTML Table數據報表、計算機鍵盤、表單對齊不支援跨列 (colspan),靈活度較低
AbsoluteLayout絕對座標 (x, y)極少 (遊戲、特殊繪圖)已棄用,不適配多螢幕

LinearLayout 詳解

<LinearLayout
    android:orientation="vertical" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button android:text="Up" android:layout_width="match_parent" android:layout_height="wrap_content"/>

    <LinearLayout android:orientation="horizontal" ...>
        <Button android:text="Left" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content"/>
        <Button android:text="Right" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content"/>
    </LinearLayout>
</LinearLayout>
  • layout_weight:垂直時分配高度、水平時分配寬度。配合 0dp 實現等分。
  • 巢狀過深 (>10 層) 會拖慢渲染,改用 ConstraintLayout/RelativeLayout 扁平化。

RelativeLayout 關鍵屬性

屬性說明
layout_below / above / toLeftOf / toRightOf相對兄弟元素 ID 定位
layout_alignParentTop / Bottom / Left / Right / CenterInParent相對父容器邊緣/中心對齊 (true/false)
layout_alignTop / Bottom / Left / Right / Baseline與兄弟元素對應邊緣/基線對齊
layout_margin*外邊距

FrameLayout 疊加範例

<FrameLayout ...>
    <ImageView android:src="@drawable/bg" android:layout_width="match_parent" android:layout_height="match_parent"/>
    <ImageView android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"/>
    <TextView android:text="覆蓋文字" android:layout_gravity="bottom|center_horizontal"/>
</FrameLayout>

TableLayout 範例

<TableLayout ...>
    <TableRow android:gravity="center">
        <Button android:text="1"/> <Button android:text="2"/> <Button android:text="3"/>
    </TableRow>
    <TableRow>
        <TextView android:text="R1C1"/> <TextView android:text="R1C2"/>
    </TableRow>
</TableLayout>

現代最佳實踐:ConstraintLayout

  • Google 推薦的扁平化佈局,結合 RelativeLayout 相對定位與 LinearLayout 權重分配。
  • 視覺化編輯器 (Layout Editor) 支援拖拽建立約束。
  • 支援 Guideline、Barrier、Chain、Group、虛擬佈局等進階功能。
  • 性能優於深層巢狀 LinearLayout/RelativeLayout。

圖示參考

五大佈局總覽

LinearLayout

TableLayout

FrameLayout

copyright © 萬盛學電腦網 all rights reserved