如何约束GridLayout的宽度小于父的宽度?

时间:2015-07-07 18:27:02

标签: android layout grid-layout

我在XML布局文件中定义了一个GridLayout:

    <GridLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnCount="4"
    android:useDefaultMargins="true" >

    <Button android:text="ababababababababababababababababababababab" />
    <Button android:text="ababababababababababababababababababababab" />
    <Button android:text="ababababababababababababababababababababab" />
    </GridLayout>

因为宽度为match_parent,我希望GridLayout排列按钮,使得每行只显示尽可能多的按钮,以保持行的宽度小于父的宽度

然而,这不是我所看到的结果。三个按钮都显示在第一行中,超出父宽度,如下图所示。实现我正在寻找的输出的方法是什么?

The output I am getting - all buttons in one row and extending beyond the parent width

1 个答案:

答案 0 :(得分:0)

GridLayout是否需要?如何改为LinearLayout并给每个视图赋予相同的权重?

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <Button
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="ababababababababababababababababababababab" />

                    <Button
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="ababababababababababababababababababababab" />

                    <Button
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="ababababababababababababababababababababab" />
                </LinearLayout>

或者将GridLayout替换为TableLayout并将按钮包装成TableRow,如下所示:

            <TableLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TableRow>
                    <Button android:text="ababababababababababababababababababababab" />
                    <Button android:text="ababababababababababababababababababababab" />
                    <Button android:text="ababababababababababababababababababababab" />
                </TableRow>
            </TableLayout>