理解measureWithLargestChild:为什么会破坏布局?

11

我正在使用选项measureWithLargestChild="true",但如果我的一个按钮的文本太大,我不明白为什么我的布局会破坏总体效果。我认为它应该保持基本大小为1/3,但它们变小了约1/6。为什么会这样呢?

这里可以看到一些屏幕截图:

Button layout bug

以下是我的XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:baselineAligned="false"
    android:gravity="center"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:baselineAligned="false"
        android:measureWithLargestChild="true" >
        <Button
            style="@style/my_style"
            android:layout_weight="1"
            android:text="Button123456" />
        <Button
            style="@style/my_style"
            android:layout_weight="1"
            android:text="A" />
        <Button
            style="@style/my_style"
            android:layout_weight="1"
            android:text="WW" />
    </LinearLayout>
</LinearLayout>
2个回答

7
我相信这是度量算法中的一个错误。在LinearLayout.measureHorizontal(int, int)方法中有以下注释。
// Either expand children with weight to take up available space or
// shrink them if they extend beyond our current bounds

它说,如果没有足够的空间容纳,算法将缩小具有 weight 的项目。由于设置了 measureWithLargestChildtrue,所有项目的宽度均与最左侧的项目相同。现在它们全部加起来无法再适应父元素的宽度。因此它们将被缩小。如果没有错误,所有项目之后都将具有相同的宽度。但由于错误,算法收缩了根据 measureWithLargestChild 属性计算而不是原始(wrap_content)宽度。这就是为什么右边的两个项目变小的原因。

有人能解释一下为什么在第二种情况中它会被缩小(四种情况中的一种)吗?为什么在这种情况下没有可用的空间? - Diffy

0
例如,如果您有一个水平的LinearLayout,并且使用了android:measureWithLargestChild="true"android:layout_width="wrap_content"属性,请确保子视图同时设置了android:layout_width="0dp"android:layout_weight="1"。否则,子视图的宽度将不会是您期望的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接