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

Android 布局屬性詳解:五大布局容器與 RelativeLayout 常用屬性一覽

編輯:關於 Android 程式設計

布局是 Android 界面的骨架。選對容器、用對屬性,才能既實現設計效果又保證性能。本文把開發中最常見的五種布局及其關鍵屬性做了一次系統梳理。

1. LinearLayout(線性布局)

線性布局把子控件按單一方向排列,是最常用的容器之一。透過 orientation 屬性決定排列方向:

android:orientation="horizontal"   
android:orientation="vertical"     

它可以在一個方向上容納多個控件,並透過 layout_weight 分配剩餘空間。使用時應注意盡量減少嵌套層數,避免影響渲染性能。

2. RelativeLayout(相對布局)

相對布局允許子控件相對於父容器或其他兄弟控件定位,靈活性很高。常用屬性可分為三類。

第一類:取值為 true / false

  • layout_centerHorizontal:水平居中
  • layout_centerVertical:垂直居中
  • layout_centerInParent:相對於父元素完全居中
  • layout_alignParentBottom:貼緊父元素下邊緣
  • layout_alignParentLeft:貼緊父元素左邊緣
  • layout_alignParentRight:貼緊父元素右邊緣
  • layout_alignParentTop:貼緊父元素上邊緣
  • layout_alignWithParentIfMissing:找不到兄弟參照時以父元素為參照

第二類:取值為 id 引用(@id/id-name)

  • layout_below:位於某元素下方
  • layout_above:位於某元素上方
  • layout_toLeftOf:位於某元素左邊
  • layout_toRightOf:位於某元素右邊
  • layout_alignTop:上邊緣與某元素上邊緣對齊
  • layout_alignLeft:左邊緣與某元素左邊緣對齊
  • layout_alignBottom:下邊緣與某元素下邊緣對齊
  • layout_alignRight:右邊緣與某元素右邊緣對齊

第三類:取值為具體尺寸(如 30dip、40px)

  • layout_marginBottom:距某元素底邊緣的距離
  • layout_marginLeft:距某元素左邊緣的距離
  • layout_marginRight:距某元素右邊緣的距離
  • layout_marginTop:距某元素上邊緣的距離

3. TableLayout(表格布局)

TableLayout 需要與 TableRow 配合使用,概念上類似 HTML 中的 table:行由 TableRow 控制,列則由該行中的控件個數決定。它不如 HTML 表格靈活,但足以應對表單類界面。

<TableLayout android:id="@+id/table01"
    android:stretchColumns="1,2,3,4">
    <TableRow>
        <EditText />
        <EditText />
    </TableRow>
    <TableRow>
        <EditText />
        <EditText />
    </TableRow>
</TableLayout>

上例即為兩行兩列的表格。其中 android:gravity="center" 可讓內容居中顯示;android:stretchColumns="1,2,3,4" 表示自動拉伸第 1 至 4 列。表格的行列也可以在代碼中動態添加:

TableLayout tableLayout = (TableLayout) findViewById(R.id.table01);
TableRow tableRow = new TableRow(this);
TextView temp = new TextView(this);
temp.setText("text 的值");
tableRow.addView(temp);
tableLayout.addView(tableRow);

4. AbsoluteLayout(絕對布局)

絕對布局允許直接指定每個控件的 x、y 坐標。它曾經常用,但因為不同屏幕尺寸下適配困難,如今已不推荐,僅在特殊場景下偶爾使用。

5. FrameLayout(幀布局)

幀布局中的子控件預設全部堆疊在左上角,後添加的控件會覆蓋前面的控件,常用於圖片切換、浮層、Fragment 容器等場景。

選型建議

能少嵌套就少嵌套,能用 ConstraintLayout 就優先使用;確需使用傳統布局時,線性與相對布局覆蓋了大多數需求,表格布局適合表單,幀布局適合層疊顯示。

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