【问题标题】:Align Buttons in GridLayout在 GridLayout 中对齐按钮
【发布时间】:2012-09-26 12:10:09
【问题描述】:

我的布局代码及其图形表示是:

这只是一个例子,我的应用程序中有大约 30 个Buttons GridLayout。 我希望我的Buttons 填充网格中的整个单元格,并且网格的列应该是均匀的宽度/高度。

我似乎无法完成它,欢迎任何帮助。

【问题讨论】:

  • 你为什么不使用线性布局,你可以将所有按钮放置在适当的高度和宽度。
  • 这基本上是一个计算器应用程序,所以网格布局似乎最好(我尝试过线性/相对布局,但网格更适合我)
  • 您希望如何放置所有 30 个按钮?它应该是一个 n X m 按钮的矩阵,都是正方形(等宽和等高)?
  • s18.postimage.org/i7rgp7tnb/Untitled_2.jpg 这是我的实际布局,你可以看到最右边的列比其他列宽,我需要所有列的宽度相同,并且每个按钮都需要完全填充它的单元格。结果应该是网格布局填满了整个屏幕,并且它的每个按钮都尽可能大。

标签: android android-button gravity grid-layout


【解决方案1】:

我没有太多使用GridLayout 来推荐有关使用它的东西,我可以向您推荐的是使用TableLayout。我这样说是因为您的布局非常适合TableLayout 的范围,并且在快速浏览GridLayout 的文档后,这似乎是一个问题:

GridLayout 不提供对权重原则的支持,如权重中定义的那样。一般来说,因此不可能配置一个 GridLayout 来在多个组件之间分配多余的空间。

ICS 中也引入了GridLayout

您可以在此处查看使用 TableLayout 的布局示例:

https://gist.github.com/3788301

如果您不希望表格填满整个高度,请从TableLayout 中删除weigthSum 属性,并从TableRows 中删除layout_weight="1"

【讨论】:

  • @aviran 如果我的回答对您有帮助,您可以通过单击复选标记接受它。这样问题就会得到解答,我们将获得一些声誉积分,您将来更有可能让用户帮助您。
  • 虽然 GridLayout 是在 ICS 中引入的,但它也存在于 v7 支持库中。
【解决方案2】:

如果 API 级别 21+,您可以使用 layout_rowWeightlayout_columnWeight

 <GridLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:columnCount="2"
        android:rowCount="2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <Button
            android:id="@+id/button1"
            android:layout_gravity="fill"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:text="Button" />
        <Button
            android:id="@+id/button2"
            android:layout_gravity="fill"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:text="Button" />
        <Button
            android:id="@+id/button3"
            android:layout_gravity="fill"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:text="Button" />
        <Button
            android:id="@+id/button4"
            android:layout_gravity="fill"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:text="Button" />

    </GridLayout>

【讨论】:

    猜你喜欢
    • 2017-11-28
    • 2019-02-04
    • 2019-11-05
    • 2018-02-05
    • 1970-01-01
    • 2013-12-26
    • 2023-03-05
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多