android:orientation="vertical":垂直堆疊(預設)。android:orientation="horizontal":水平排列。| 值 | 行為 |
|---|---|
| match_parent / fill_parent | 填滿父容器 |
| wrap_content | 包裹內容大小 |
| 具體 dp/sp | 固定尺寸 |
子元素設定 android:layout_weight,剩餘空間按權重比例分配。
<LinearLayout android:orientation="vertical" ...>
<EditText android:layout_weight="1" android:layout_height="0dp" ... /> <!-- 佔滿剩餘高度 -->
<Button android:layout_height="wrap_content" ... /> <!-- 不佔權重 -->
<TextView android:layout_weight="1" android:layout_height="0dp" ... /> <!-- 佔滿剩餘高度 -->
</LinearLayout>
0dp(vertical 用 height,horizontal 用 width)。layout_weight 否則會佔滿空間。| 屬性 | 說明 |
|---|---|
| android:id | 元件唯一識別,供 findViewById 使用 |
| android:text | 顯示文字,建議引用 @string/ |
| android:gravity | 內容對齊(center, left, right...) |
| android:textSize | 字體大小 (sp) |
| android:background | 背景色/圖 |
| android:padding | 內邊距 |
| android:singleLine | 強制單行顯示 |
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText android:id="@+id/edtInput"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button android:id="@+id/myButton"
android:layout_width="match_parent" android:layout_height="wrap_content" />
<TextView android:id="@+id/firstText"
android:layout_width="match_parent" android:layout_height="0dp"
android:layout_weight="1"
android:text="TextView第一行" android:gravity="center_vertical"
android:textSize="15pt" android:background="#aa0000"
android:singleLine="true" />
</LinearLayout>
LinearLayout 簡單高效,掌握 orientation、wrap_content/match_parent、layout_weight(0dp) 三大核心即可構建大多數線性介面。