2.2.1 LinearLayout(线性布局)权重算法、分割线与对齐约束详解
全面解析 LinearLayout 的水平/垂直排列机制、0dp/wrap_content/match_parent 三种尺寸下 layout_weight 精确数学计算公式、分割线两种实现方式、嵌套表单实例及 layout_gravity 交叉轴生效规则。
学完这一章,你能够
- 全面解析 LinearLayout 的水平/垂直排列机制、0dp/wrap_content/match_parent 三种尺寸下 layout_weight 精确数学计算公式、分割线两种实现方式、嵌套表单实例及 layout_gravity 交叉轴生效规则。
六大传统布局定位与 LinearLayout 权重基础
Android 传统视图体系包含六大基础布局:`LinearLayout`(线性布局)、`RelativeLayout`(相对布局)、`TableLayout`(表格布局)、`FrameLayout`(帧布局)、`GridLayout`(网格布局)与已废弃的 `AbsoluteLayout`(绝对布局)(现代复杂界面还广泛采用扁平化的 `ConstraintLayout`)。`LinearLayout` 将子控件沿 `android:orientation` 指定的水平(`horizontal`,默认)或垂直(`vertical`)单轴依次排布,其最具代表性的屏幕适配能力就是 `android:layout_weight` 权重按比例分配。
最标准且推荐的等比例划分写法是将分配方向上的尺寸设为 `0dp` 再赋予权重:例如在水平 `LinearLayout` 中,两个子布局均设 `android:layout_width="0dp"`,权重分别设 `1` 与 `2` 即精确得到 `1:2` 宽度(改为 `1` 与 `1` 即 `1:1` 均分);垂直方向同理,将 `android:layout_height` 设为 `0dp` 再配 `layout_weight`。这种写法的底层原因是跳过内容初次测量,直接把父容器 `100%` 宽度作为剩余空间按权重切分,既精确又减少测量耗时。
wrap_content 与 match_parent 下的权重数学公式与代码设置
若不写 `0dp` 而改用 `wrap_content` 或 `match_parent`(旧称 `fill_parent`),就必须理解 Android 内部统一的权重分配公式:`最终尺寸 = 控件初始测量尺寸 + 剩余空间 × (自身权重 / 总权重)`,其中 `剩余空间 = 父容器尺寸 - 所有子控件初始尺寸之和`。当三个 `TextView`(文本 `one`、`two`、`three`)宽度为 `wrap_content` 且权重为 `1:2:3` 时,系统先各自保留文本固有宽度,再把剩余正空间按 `1/6`、`2/6`、`3/6` 叠加——因此最终并非严格 `1:2:3`(本站实验在 `300dp` 父宽、固有宽 `30/30/48dp` 下算得精确结果 `[62, 94, 144]`)。
更反直觉的现象发生在全部子控件设为 `match_parent`/`fill_parent` 时:三个宽度均为 `1W`(父宽)的 `TextView` 叠加总初宽为 `3W`,导致剩余空间为负数 `W - 3W = -2W`。当权重为 `1:2:3`(总和 `6`)时,三者最终宽度依次为 `1 - 2×(1/6) = 2/3 W`、`1 - 2×(2/6) = 1/3 W` 与 `1 - 2×(3/6) = 0`,原本权重最大的 `three` 反而被压缩至 `0` 彻底消失(呈现 `2:1:0`);同理,权重 `1:1:1` 得到 `1/3 : 1/3 : 1/3`,权重 `2:3:4`(总和 `9`)得到 `5/9 : 3/9 : 1/9`(即 `5:3:1`)。若需在 Java 代码中动态指定权重,可构造三参 `LinearLayout.LayoutParams(width, height, weight)` 传入 `setLayoutParams()`(现代常量推荐 `LayoutParams.MATCH_PARENT` 替代旧 `FILL_PARENT`)。
分割线两种实现、表单示例与 layout_gravity 交叉轴陷阱
在注册表单或菜单列表中为 `LinearLayout` 子项绘制分割线有两种常见做法:方式一是在相邻控件间直接插入一个极细的纯色 `<View android:layout_width="match_parent" android:layout_height="1px" android:background="#000000" />`(高分屏常改用 `1dp` 或 `0.5dp`);方式二是利用 `LinearLayout` 原生分割线属性——`android:divider` 指定线条 Drawable(图片或 `<shape>` XML)、`android:showDividers` 控制出现位置(`none`/`beginning`/`end`/`middle`,三个按钮设 `middle` 恰好生成 2 条中间分隔线)、`android:dividerPadding` 设定分割线两端缩进(如 `10dp`)。
综合基础属性可快速组合常见输入界面:外层采用垂直 `LinearLayout` 依次放置提示 `TextView`、占满宽度的 `EditText`,底部再嵌套一个水平子 `LinearLayout` 并设 `android:gravity="right"`(现代国际化建议 `end`),将“保存”与“清空”两个按钮整齐右对齐。
使用 `android:layout_gravity` 时存在一条初学者极易踩坑的核心规则:`LinearLayout` 中的 `layout_gravity` 只在与 `orientation` 垂直的交叉轴上生效!当 `orientation="horizontal"` 时,子控件沿主轴依次紧邻排布,因此子控件上的 `left`/`right`/`center_horizontal` 全部被忽略,仅 `top`/`bottom`/`center_vertical` 生效;反之当 `orientation="vertical"` 时,仅 `left`/`right`/`center_horizontal` 生效,垂直方向设置无效。所以想在水平行里让两个控件一左一右分置两端,仅设 `layout_gravity="left"` 与 `right` 必然失败(即便外层加 `gravity="left"` 也无济于事);正确做法要么在中间插入 `layout_weight="1"` 的空白 `Space`/`View` 撑开,要么直接改用 `RelativeLayout` 或现代 `ConstraintLayout`。
运行 LinearLayout 权重(0dp/wrap_content/fill_parent 反比)、分割线与 layout_gravity 交叉轴离线求解器
展开查看收起
"""Offline deterministic verifier for Android CH16 (tutorial-linearlayout)."""
from __future__ import annotations
import json
import xml.etree.ElementTree as ET
from fractions import Fraction
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
def distribute_linear_weights(parent_size: int, base_sizes: list[int], weights: list[int]) -> list[Fraction]:
remaining = Fraction(parent_size - sum(base_sizes))
total_w = Fraction(sum(weights))
return [Fraction(b) + remaining * (Fraction(w) / total_w) for b, w in zip(base_sizes, weights)]
def case_weight_zero_dp_and_wrap() -> dict:
xml_zero = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal">
<LinearLayout android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1"/>
<LinearLayout android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="2"/>
</LinearLayout>"""
xml_wrap = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal">
<TextView android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="one"/>
<TextView android:layout_weight="2" android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="two"/>
<TextView android:layout_weight="3" android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="three"/>
</LinearLayout>"""
r_zero = ET.fromstring(xml_zero)
w_zero = [int(c.attrib[f"{ANDROID_NS}layout_weight"]) for c in r_zero]
res_1_2 = [int(x) for x in distribute_linear_weights(300, [0, 0], w_zero)]
res_1_1 = [int(x) for x in distribute_linear_weights(300, [0, 0], [1, 1])]
r_wrap = ET.fromstring(xml_wrap)
w_wrap = [int(c.attrib[f"{ANDROID_NS}layout_weight"]) for c in r_wrap]
# Intrinsic widths: "one"=30dp, "two"=30dp, "three"=48dp; remaining = 300 - 108 = 192dp
res_wrap = [int(x) for x in distribute_linear_weights(300, [30, 30, 48], w_wrap)]
java_lp = "setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1));"
actual = {
"zero_dp_1_2_on_300": res_1_2,
"zero_dp_1_1_on_300": res_1_1,
"wrap_content_1_2_3_on_300": res_wrap,
"java_layoutparams_weight_arg": 1 if ", 1))" in java_lp else 0,
}
expected = {
"zero_dp_1_2_on_300": [100, 200],
"zero_dp_1_1_on_300": [150, 150],
"wrap_content_1_2_3_on_300": [62, 94, 144],
"java_layoutparams_weight_arg": 1,
}
return {
"name": "linearlayout_weight_zero_dp_and_wrap_content",
"summary": "解析 0dp 与 wrap_content 下 LinearLayout 权重分配公式及 Java LayoutParams 权重构造",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_weight_match_parent_inversion() -> dict:
xml_fill = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView android:layout_weight="1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="one"/>
<TextView android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="two"/>
<TextView android:layout_weight="3" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="three"/>
</LinearLayout>"""
root = ET.fromstring(xml_fill)
w_123 = [int(c.attrib[f"{ANDROID_NS}layout_weight"]) for c in root]
# Parent width normalized to 1 unit; each fill_parent child starts at 1 unit
r_123 = [str(f) for f in distribute_linear_weights(1, [1, 1, 1], w_123)]
r_111 = [str(f) for f in distribute_linear_weights(1, [1, 1, 1], [1, 1, 1])]
r_234 = [str(f) for f in distribute_linear_weights(1, [1, 1, 1], [2, 3, 4])]
actual = {
"fill_parent_1_2_3": r_123,
"fill_parent_1_1_1": r_111,
"fill_parent_2_3_4": r_234,
"three_collapses_to_zero": r_123[2] == "0",
}
expected = {
"fill_parent_1_2_3": ["2/3", "1/3", "0"],
"fill_parent_1_1_1": ["1/3", "1/3", "1/3"],
"fill_parent_2_3_4": ["5/9", "1/3", "1/9"],
"three_collapses_to_zero": True,
}
return {
"name": "linearlayout_weight_match_parent_inversion",
"summary": "验证 fill_parent/match_parent 下权重反比公式(1:2:3->2/3:1/3:0、1:1:1、2:3:4->5/9:1/3:1/9)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_divider_and_form() -> dict:
view_line = '<View xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="1px" android:background="#000000" />'
div_xml = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:divider="@drawable/ktv_line_div" android:orientation="vertical"
android:showDividers="middle" android:dividerPadding="10dp">
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮1" />
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮2" />
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮3" />
</LinearLayout>"""
form_xml = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="请输入要保存的电话号码"/>
<EditText android:layout_width="fill_parent" android:layout_height="wrap_content"/>
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="right">
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="保存"/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="清空"/>
</LinearLayout>
</LinearLayout>"""
v_el = ET.fromstring(view_line)
d_root = ET.fromstring(div_xml)
f_root = ET.fromstring(form_xml)
btn_count = len(list(d_root))
show = d_root.attrib[f"{ANDROID_NS}showDividers"]
middle_dividers = max(0, btn_count - 1) if show == "middle" else 0
inner_bar = f_root.find("LinearLayout")
assert inner_bar is not None
actual = {
"view_divider_height": v_el.attrib[f"{ANDROID_NS}layout_height"],
"middle_divider_slots": middle_dividers,
"divider_padding": d_root.attrib[f"{ANDROID_NS}dividerPadding"],
"nested_button_bar_gravity": inner_bar.attrib[f"{ANDROID_NS}gravity"],
"nested_buttons": [b.attrib[f"{ANDROID_NS}text"] for b in inner_bar],
}
expected = {
"view_divider_height": "1px",
"middle_divider_slots": 2,
"divider_padding": "10dp",
"nested_button_bar_gravity": "right",
"nested_buttons": ["保存", "清空"],
}
return {
"name": "linearlayout_divider_and_form_layout",
"summary": "解析 1px View 分割线、android:divider/showDividers=middle 槽位数及嵌套表单右对齐按钮栏",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_gravity_axis_constraint() -> dict:
def effective_layout_gravity(orientation: str, flags: list[str]) -> list[str]:
if orientation == "vertical":
allowed = {"left", "right", "start", "end", "center_horizontal"}
else:
allowed = {"top", "bottom", "center_vertical"}
return [f for f in flags if f in allowed]
xml_horiz = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:gravity="left">
<TextView android:layout_width="wrap_content" android:layout_height="200dp" android:layout_gravity="left" android:gravity="center" android:text="A" />
<TextView android:layout_width="wrap_content" android:layout_height="200dp" android:layout_gravity="right" android:gravity="center" android:text="B" />
</LinearLayout>"""
root = ET.fromstring(xml_horiz)
orient = root.attrib[f"{ANDROID_NS}orientation"]
child_lgs = [c.attrib[f"{ANDROID_NS}layout_gravity"] for c in root]
actual = {
"horizontal_child_effective_lgs": [effective_layout_gravity(orient, [lg]) for lg in child_lgs],
"horizontal_allows_bottom": effective_layout_gravity("horizontal", ["right", "bottom"]),
"vertical_allows_right": effective_layout_gravity("vertical", ["right", "bottom"]),
}
expected = {
"horizontal_child_effective_lgs": [[], []],
"horizontal_allows_bottom": ["bottom"],
"vertical_allows_right": ["right"],
}
return {
"name": "linearlayout_gravity_axis_constraint",
"summary": "验证 LinearLayout 中 layout_gravity 仅在交叉轴生效(horizontal 忽略 left/right,vertical 忽略 top/bottom)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main() -> None:
payload = {
"version": "CPython 3.12.14 offline Android XML/layout/manifest verifier (Android SDK/emulator absent)",
"cases": [
case_weight_zero_dp_and_wrap(),
case_weight_match_parent_inversion(),
case_divider_and_form(),
case_gravity_axis_constraint(),
],
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为三个 `match_parent` 子控件初始总宽为 `3W`,剩余空间为 `-2W`,第 3 个控件按 `3/6` 扣减后剩余 `W - 2W×(3/6) = 0`;将三个子控件的 `layout_width` 全部改为 `0dp` 即可把整行宽度严格按 `1:2:3` 切分。