素材巴巴 > 程序开发 >

android布局-GridLayout

程序开发 2023-09-15 22:10:32

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


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


3、常用属性

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


4、一个经典的案例


    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnCount="4"
    android:orientation="horizontal"
    android:rowCount="3" >


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

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

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

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

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

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

效果图:

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

    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无法在水平和垂直方向扩展,

效果如下:













标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。