android布局-GridLayout

本文详细介绍了GridLayout的基本用法,包括如何设置行列数、组件的跨行跨列显示等特性,并通过一个具体示例展示了如何使用这些属性来实现灵活的布局。

1、GridLayout将整个容器划分成columnCount * rowCount个网格(columnCount ,rowCount是GridLayout的两个属性,用于指定该布局的行和列), 每个网格可以放置一个组件. 还可以设置一个组件横跨多少列, 多少行. 不存在一个网格放多个组件情况


2、GridLayout的行并不固定。原因是这个网格并不会因为我们指定制定了行数而固定不变,如果我们创建的组件比网格数量多,那么它会自动到下一行。


3、常用属性

  layout_row、layout_column指定组件的行列
  layout_columnSpan 设置该子组件在GridLayout中横向跨几列
  layout_rowSpan设置该子组件在GridLayout纵向横跨几行


4、一个经典的案例

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnCount="4"
    android:orientation="horizontal"
    android:rowCount="3" >


    <Button
        android:id="@+id/one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1" />

    <Button
        android:id="@+id/two"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="2" />
    
     <Button
        android:id="@+id/two"
        android:text="2" />

    <Button
        android:id="@+id/three"
        android:layout_width="wrap_content"
        android:layout_gravity="fill"
        android:text="3" />   
  

    <Button
        android:id="@+id/five"
        android:layout_columnSpan="2"
        android:layout_gravity="fill"
        android:text="4" />
      

    <Button
        android:id="@+id/five"
        android:text="5" />

    <Button
        android:id="@+id/six"
        android:layout_gravity="fill"
        android:layout_rowSpan="2"
        android:text="6" />
    
    <Button
        android:id="@+id/seven"
        android:text="7" />
    
    <Button
        android:id="@+id/eight"
        android:text="8" />
    
    <Button
        android:id="@+id/nine"
        android:text="9" />

</GridLayout>

效果图:

5、有几个重要地方一定要注意:

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

。。。

在GridLayout的 android:layout_width的属性必须指定为match_parent或者fill_parent,如果指定为wrap_content,会导致按钮3和6无法占满右侧剩余的空间,

效果如下:



6、我们在对按钮进行布局的时候,我们可以采用两种方式:

(1)直接将按钮依次排列,让按钮自动换行

(2)利用GridLayout 中layout_row、layout_column两个属性指定按钮位于哪一个网格中。需要注意的是网格的行和列的序号都是从0开始,所以使用此方法时,我们要注意正确的使用行列的编号。



7、跨行和跨列

我们要实现GridLayout 的跨行和列需要用到:

layout_columnSpan
layout_rowSpan

说明:按钮3和6并没有使用跨列,6仅仅使用了跨行,同时设置android:layout_gravity="fill"

按钮4在使用layout_columnSpan="2"后,此组件还要加上 android:layout_gravity="fill",否则无法实现组件扩展,而导致一个位置空出


按钮6:

layout_rowSpan="2"(跨行)

 此属性也必须同时设置,android:layout_gravity="fill",如果不设置会导致按钮6无法在水平和垂直方向扩展,

效果如下:












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值