現象:外層 LinearLayout 期望垂直排列(第一行 4 TextView,第二行 Button),但所有控件擠在同一水平行。
<LinearLayout ... android:orientation="vertical"> <!-- 缺失 orientation -->
<!-- 4 TextView 直接放這裡 -->
<LinearLayout android:orientation="vertical" ...> <!-- 內層也垂直 -->
<Button ... />
</LinearLayout>
</LinearLayout>
問題:
android:orientation="vertical"**,默認 horizontal,導致所有直接子元素(4 TextView + 內層 LinearLayout)水平排列。orientation="vertical" 對單個 Button 無意義。<LinearLayout xmlns:android="..."
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"> <!-- 關鍵:外層垂直 -->
<!-- 第 1 行:4 個 TextView 水平排列 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<TextView ... /> <TextView ... /> <TextView ... /> <TextView ... />
</LinearLayout>
<!-- 第 2 行:Button 置中 -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Submit" />
</LinearLayout>
| 層級 | orientation | 作用 |
|---|---|---|
| 根容器 | vertical | 行級垂直堆疊 |
| 行容器 | horizontal | 列級水平排列 |
| 單控件行 | 無需嵌套 | 直接放根容器,用 layout_gravity 置中 |
扁平化佈局,用約束實現同樣效果,性能更優:
<ConstraintLayout ...>
<TextView android:id="@+id/t1" ... app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView ... app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="@id/t1" />
<Button ... app:layout_constraintTop_toBottomOf="@id/t1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</ConstraintLayout>
明確每層 orientation,或遷移至 ConstraintLayout,告別佈局錯位。