05 常用布局¶
安卓界面 = 布局(怎么排) + 控件(显示什么)。本章介绍三种最常用布局。
5.1 LinearLayout(线性布局)¶
控件按水平/垂直排成一列:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <!-- vertical 纵向 / horizontal 横向 -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第一行" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="第二行" />
<!-- layout_weight:按比例分配剩余空间 -->
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="占满剩余空间" />
</LinearLayout>
orientation="vertical"从上到下排;"horizontal"从左到右排;layout_weight配合0dp高度/宽度 = 按权重瓜分空间(类似 CSS flex-grow)。
5.2 RelativeLayout(相对布局)¶
子控件相对父容器或兄弟控件定位:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" <!-- 贴父容器底部 -->
android:layout_centerHorizontal="true" <!-- 水平居中 -->
android:text="确定" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/btnOk" <!-- 在按钮上方 -->
android:text="按钮上面的文字" />
</RelativeLayout>
常用属性:layout_alignParentTop/Bottom/Left/Right、layout_centerInParent、layout_toRightOf、layout_above、layout_below。
5.3 ConstraintLayout(约束布局,官方主力)¶
性能好、可视化拖拽方便,AS 新建布局默认就是它。核心思想:每个控件用约束钉在别的控件/父容器上:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/etInput"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="输入内容"
app:layout_constraintStart_toStartOf="parent" <!-- 左对齐父容器 -->
app:layout_constraintEnd_toEndOf="parent" <!-- 右对齐父容器 -->
app:layout_constraintTop_toTopOf="parent" /> <!-- 顶部对齐父容器 -->
<Button
android:id="@+id/btnGo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GO"
app:layout_constraintTop_toBottomOf="@id/etInput" <!-- 在输入框下方 -->
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
- 控件必须至少水平方向一条 + 垂直方向一条约束,否则会"飘"到左上角;
- 拖拽模式下点控件四角小圆点拉到目标即可生成约束;
0dp表示"由约束决定尺寸"(match_constraint)。
5.4 布局小技巧¶
| 需求 | 做法 |
|---|---|
| 整屏上下左右居中 | ConstraintLayout:layout_constraintTop_toTopOf="parent" + Bottom_toBottomOf + 左右同理;或 android:layout_gravity="center" |
| 吸底按钮 | LinearLayout 竖排,按钮 layout_weight="0" 放最后即可;或 ConstraintLayout 约束到底部 |
| 控件间距 | android:layout_marginTop="16dp"(外边距)、android:padding="8dp"(内边距) |
| 多个控件水平均分 | LinearLayout 横向 + 每个 layout_width="0dp" + layout_weight="1" |
💡 新建布局时 AS 右侧有 Design / Split / Code 三个视图,拖拽 + 手写结合最效率。报"约束不足"的黄线提示时补两条约束即可。
本章练习:用 ConstraintLayout 做一个"顶部标题 + 中间输入框 + 底部按钮"的界面。