实际上用过TableLayout来作表格的人估计都碰到过,TableLayout有根据cell内容长度自动扩展的特点(要保证表格不变形,只能自己断行),如果cell合并,当合并cell太长时,自动扩展所在列的宽度,而不是根据合并后的列宽度来扩展,例子如下:
<screen title="TableLayout Demo">
<scrollpane scrollbar="both">
<container style="layout:tablelayout;gap:1 1;border:1 1 1 1;border-color:red;bg-color:red;font-size:large">
<text class="child1" style="min-size:30 0">姓名</text>
<text class="child1" style="min-size:50 0">部门</text><break/>
<text class="child1" style="span:2 1">我们是更加重视下拉</text>
</container>
</scrollpane>
<screenfirstmenu onAction="back">Back</screenfirstmenu>
<screenSecondMenu onAction="exit">Exit</screenSecondMenu>
</screen>
第二行采用合并单元格,结果第一列被迫扩展到必须包含合并cell文字的长度,效果如下图:

实际上在计算每列最小宽度时,作者偷了个懒,直接用所在列中最大长度的widget作为列宽度,而没有计算它合并的列,虽然实际上它确实对合并列做了一些处理.有兴趣的人可以看看它的align函数,这个函数可不是对齐,是计算每一列宽度
/**
* shappycom
* @param first 链表
* @param values 返回值(width/height)
* @param weights
* @param horizontal
* @param fullSize 减去边界和间隔后可用的长度
*/
private static final void align(Metrics first, int[] values, int[] weights, boolean horizontal, int fullSize) {
for (int size = 1, next = 0; size != 0; size = next, next = 0) {
for (Metrics metrics = first; metrics != null; metrics = metrics.next) {
Span span = metrics.widget.getSpan();
int orientedSpan = horizontal ? span.colspan : span.rowspan;
if (orientedSpan == size) {
int value;
if (weights != null) {
value = horizontal ? metrics.width : metrics.height;
} else {
Weight weight = metrics.widget.getWeight();
value = horizontal ? weight.weightx : weight.weighty;
}
int index = horizontal ? metrics.x : metrics.y;
if (weights != null && weights[index] != 0) {
value = MathFP.toInt(MathFP.mul(weights[index], MathFP.toFP(fullSize)));
}
values[index] = Math.max(values[index], value);
} else if ((orientedSpan > size) && ((next == 0) || (next > orientedSpan))) {
next = orientedSpan;
}
}
}
}
修改后效果图:

本文探讨了使用TableLayout布局时遇到的问题,特别是当合并单元格的内容过长时导致列宽自动扩展的现象。通过分析源代码中的align函数,揭示了这一行为背后的实现原理,并提供了解决方案。
120

被折叠的 条评论
为什么被折叠?



