用途
该页面针对 Jetpack Compose 的 Row/Column 布局,解释 weight(1f, fill = false) 在什么情况下会改变布局结果,以及为什么应将它和 Arrangement.Center 成对使用。示例场景是一个 Row:由内容决定宽度的胶囊标签组、一个间距和一个固定尺寸按钮,整体希望表现为居中的一簇。
主要能力
- 说明 Row 的测量顺序:先测量无权重子项(示例中的 12dp Spacer 和 56dp 按钮),再把剩余宽度按权重分槽。
- 澄清
fill的含义:fill = true(默认)时,带权重子项以minWidth = slotWidth被测量;fill = false时以minWidth = 0被测量。它控制的是子项是否被强制把槽位宽度上报为自身尺寸,而不是“内容能否拉伸”。 - 指出当带权重子项为 filled 时,子项宽度之和恰好等于整行宽度,排布没有剩余空间可分配,
Arrangement.Center变成空操作,按钮贴边并留下空洞;释放后胶囊按内容宽度上报,剩余空间由排布在簇前后各分一半。 - 列出多个陷阱:出错的是“邻居”而非带权重子项本身;只改
fill = false不够,还必须同时改排布方式,默认Arrangement.Start会把释放的宽度收到最后一个子项之后;filled 的带权重子项还会让SpaceBetween和SpaceAround失效;该问题只在内容未占满预算时出现,改变窗口大小无法复现,需改变内容;去掉 weight 是另一种布局,不等价;带权重子项无法把无权重兄弟项推出边界;BoxWithConstraints在fill = false下仍上报完整槽位为maxWidth,只是最小值降为 0;子项内部调用fillMaxWidth()会抵消释放效果;释放出的宽度归排布而非另一个带权重子项;同一发布窗口内多处出现说明默认值本身是问题来源。
使用方式
页面给出三步排查命令(保留原文):
# 1. Weighted children against released ones. The first is a large number in any Compose codebase,
# the second a short list — read every hit in it and name the sibling it is making room for.
grep -rn --include="*.kt" -E "\.weight\(" . | grep -v "/build/" | wc -l
grep -rn --include="*.kt" "weight(1f, fill = false)" . | grep -v "/build/"
# 2. Each release next to the arrangement of the row it sits in. A hit preceded by an
# `Arrangement.Center` line is a centred cluster; a hit that prints alone is relying on Start —
# correct for a trailing label, wrong for anything meant to be centred. Keep the window wide: a
# row's arrangement sits above ALL its children, which can be thirty lines up, and at -B10 a
# correctly centred cluster prints alone and reads as a defect.
grep -rn --include="*.kt" -B30 "weight(1f, fill = false)" . | grep -v "/build/" \
| grep -E "horizontalArrangement|verticalArrangement|weight\(1f, fill = false\)"
# 3. When each site arrived. Several inside one release window, in unrelated files, is the signal.
git log -S'fill = false' --format='%h %ad %s' --date=short -- '*.kt'
验证时缩小内容而非窗口:关闭某项的显示开关让条目从四个变两个,或给字段输入一个单词值。filled 时邻居贴边且间隙随内容缩小而增大,这种反比关系即为确认;正确居中时邻居会向内移动。在内容占满时两种设置无法区分,因此需在最长内容下再测一次,这也是“直接去掉 weight”会失败而本方案不会的场景。
适用场景
适用于 Compose 中需要让一组内容整体居中、同时保留带权重子项只在固定兄弟项之后占用剩余宽度的布局;也适用于排查“邻居贴边、旁边出现可疑空洞”的布局缺陷,以及审计代码库中 fill = false 的分布。
限制
页面未提供该技能的安装命令、运行环境、收费方式或平台支持信息。相关链接:nav-tab-registration-drift(条目数量本身是条件性的,改变它会暴露 filled 槽位)与 responsive-gate-size-not-platform(自适应行的另一半:排布负责内容尺寸,门控负责窗口形状)。