2. 布局基础
任务说明
本案例使用 LinearLayout 实现两种基础排列方式:水平排列的按钮组和垂直排列的文本块。通过一个完整的 activity_main.xml 布局文件,展示线性布局的核心属性(orientation、layout_weight、gravity 等)在实际界面中的效果。
布局结构设计
整体采用垂直方向的根 LinearLayout,内部包含两个子区域:
- 水平按钮区:一个水平方向的
LinearLayout,内含三个等宽按钮,使用layout_weight="1"实现均分。 - 垂直文本区:一个垂直方向的
LinearLayout,内含三段文本,使用layout_margin控制间距,gravity控制对齐方式。
实现代码
创建 res/layout/activity_main.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<!-- 水平排列的按钮组 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="24dp">
<Button
android:id="@+id/btn_left"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="左" />
<Button
android:id="@+id/btn_center"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:text="中" />
<Button
android:id="@+id/btn_right"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="右" />
</LinearLayout>
<!-- 垂直排列的文本块 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#F5F5F5"
android:padding="12dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="第一行:垂直布局示例"
android:textSize="16sp"
android:textColor="#333333"
android:layout_marginBottom="8dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="第二行:使用 orientation 控制方向"
android:textSize="16sp"
android:textColor="#333333"
android:layout_marginBottom="8dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="第三行:layout_weight 实现等分"
android:textSize="16sp"
android:textColor="#333333" />
</LinearLayout>
</LinearLayout>
关键属性说明
| 属性 | 作用 | 本案例中的使用 |
|---|---|---|
orientation | 设置子元素排列方向 | 根布局为 vertical,按钮区为 horizontal,文本区为 vertical |
layout_weight | 按比例分配剩余空间 | 三个按钮均设为 1,实现水平等宽 |
layout_width="0dp" | 配合 weight 使用,使宽度完全由权重决定 | 按钮宽度设为 0dp,由 weight 控制 |
layout_margin | 设置外边距 | 按钮间距 8dp,文本间距 8dp,整体边距 16dp |
gravity | 控制子元素对齐方式 | 文本区使用默认左对齐,可通过 gravity 调整 |
界面布局示意
落地与验证
运行方式:在 Android Studio 中新建项目,将上述 XML 替换 res/layout/activity_main.xml 的默认内容,保持 MainActivity 中 setContentView(R.layout.activity_main) 不变,直接运行应用。
验证方法:
- 启动应用后,观察界面顶部是否出现三个水平等宽排列的按钮(左、中、右),且按钮之间留有均匀间距;
- 按钮下方是否出现灰色背景区域,其中包含三行垂直排列的文本,文本自上而下依次显示;
- 旋转设备(或调整模拟器方向),确认布局仍保持“按钮水平、文本垂直”的结构不变。
判定标准:界面呈现与上述 SVG 示意图一致,即按钮行水平均分、文本行垂直堆叠,且无元素重叠或溢出屏幕,即可判定布局实现正确。