常用屬性:
排列對齊:
①設置組件的排列方式: android:orientation="" vertical(豎直,默認)或者horizontal(水平)
②設置組件的對齊方式: android:layout_gravity="" center,left,right,buttom啊,這些,如果想同時用兩種的話:eg: buttom|left
設置布局為幾行幾列:
①設置有多少行:android:rowCount="4" //設置網格布局有4行
②設置有多少列:android:columnCount="4" //設置網格布局有4列
設置某個組件位於幾行幾列
注:都是從0開始算的哦!
①組件在第幾行:android:layout_row = "1" //設置組件位於第二行
②組件在第幾列:android:layout_column = "2" //設置該組件位於第三列
設置某個組件橫跨幾行幾列:
①橫跨幾行:android:layout_rowSpan = "2" //縱向橫跨2行
②橫跨幾列:android:layout_columnSpan = "3" //橫向橫跨2列
使用實例:
最最最普遍的例子----計算器界面:
效果圖:
PS:這里要說一點,網格布局和其他布局不同,可以不為組件設置Layout_width和Layout_height屬性
因為組件的寬高由幾行幾列決定了,當然,你也可以寫個wrap_content
代碼:
- <GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/GridLayout1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:rowCount="6"
- android:columnCount="4"
- android:orientation="horizontal">
- <TextView
- android:layout_columnSpan="4"
- android:text="0"
- android:textSize="50sp"
- android:layout_marginLeft="5dp"
- android:layout_marginRight="5dp"
- />
- <Button
- android:text="回退"
- android:layout_columnSpan="2"
- android:layout_gravity="fill"
- />
- <Button
- android:text="清空"
- android:layout_columnSpan="2"
- android:layout_gravity="fill"
- />
- <Button
- android:text="+"
- />
- <Button
- android:text="1"
- />
- <Button
- android:text="2"
- />
- <Button
- android:text="3"
- />
- <Button
- android:text="-"
- />
- <Button
- android:text="4"
- />
- <Button
- android:text="5"
- />
- <Button
- android:text="6"
- />
- <Button
- android:text="*"
- />
- <Button
- android:text="7"
- />
- <Button
- android:text="8"
- />
- <Button
- android:text="9"
- />
- <Button
- android:text="/"
- />
- <Button
- android:layout_width="wrap_content"
- android:text="."
- />
- <Button
- android:text="0"
- />
- <Button
- android:text="="
- />
- </GridLayout>
代碼解釋:
代碼很簡單,就是清除和回退按鈕設置了跨兩列而已,其他的都是直接添加的
每個組件默認是占一行,占一列
這里要說明一點:
通過android:layout_rowSpan和android:layout_columnSpan設置表明組件橫越的行數與列數
再通過:android:layout_gravity = "fill" 設置表明組件填滿所橫越的整行或者整列
用法總結:
①GridLayout使用虛細線將布局划分為行,列和單元格,同時也支持在行,列上進行交錯排列
②使用流程:
step 1:先定義組件的對其方式 android:orientation 水平或者豎直
step 2:設置組件所在的行或者列,記得是從0開始算的
step 3:設置組件橫跨幾行或者幾列;設置完畢后,需要在設置一個填充:android:layout_gravity = "fill"
另外:這些屬性也常用到:
<GridView android:id="@+id/grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:verticalSpacing="35px" <!-- grid元素之間的豎直間隔 -->
android:horizontalSpacing="5px" <!--grid元素之間的水平間隔 -->
android:numColumns="auto_fit" <!--表示有多少列,如果設置為auto_fit,將根據columnWidth和Spacing來自動計算 -->
android:columnWidth="100px" <!-- 一般建議采用有像素密度無關的dip或者dp來表示-->
android:stretchMode="columnWidth" <!--如何填滿空余的位置,模擬器采用WVGA800*480,每排4列,有4*100+5*3=415,還余65px的空間,如果是columnWidth,則這剩余的65將分攤給4列,每列增加16/17px。如果采用SpacingWidth,則分攤給3個間隔空隙 -->
android:gravity="center" />