网格布局管理器GridLayout类来表示。在《从零开始学android编程之格布局管理器》中提到的TableLayout一般产生的表格外形是标准的方框,而GridLayout类产生的网格可以是不标准的。

1 设置网格的行数和列数

在《从零开始学android编程之线性布局管理器》中提到的activity_linear.xml文件中使用表格布局管理器GridLayout,代码如下

<LinearLayout

android:orientation="vertical"

.........
    
>
    <GridLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按键1"
/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按键2"
/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按键3"
/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按键4"
/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按键5"
/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按键6"
/>
    </GridLayout>

</LinearLayout>

表格布局管理器GridLayout中添加了6Button组件,效果如图1所示。从图1可以看出,在未设置表格布局管理器的行数和列数时,该管理器的效果与线性布局管理器的横向排列效果相同

 

从零开始学android编程之网格布局管理器(2-1)

可以通过表格布局管理器GridLayoutandroid:columnCount属性来设置表格的列数,通过android:rowCount属性设置表格的行数。需要注意的是,在使用android:columnCount属性时,必须将表格布局管理器android:orietation属性设置为horizontal;而使用android:rowCount属性时必须将android:orietation属性设置为vertical。代码如下所示

<GridLayout

.........
    android:orientation="vertical"
    android:rowCount="3"
    
>
</GridLayout>

以上代码将6Button组件分成了3×2的网格,如图2所示。

从零开始学android编程之网格布局管理器(2-1) 


相关文章:

  • 2022-12-23
  • 2021-09-03
  • 2022-12-23
  • 2021-11-30
  • 2021-10-04
  • 2021-11-12
  • 2021-10-18
  • 2022-12-23
猜你喜欢
  • 2021-11-22
  • 2022-12-23
  • 2021-06-23
  • 2021-07-21
  • 2021-11-30
  • 2022-12-23
  • 2021-07-29
相关资源
相似解决方案