標籤:
作者:李響
本文重點講述了自android4.0版本號碼後新增的GridLayout網格布局的一些基本內容,並在此基礎上實現了一個簡單的計算機布局架構。通過本文,您可以瞭解到一些android UI開發的新特性,並可以實現相關應用。
在android4.0版本號碼之前,假設想要達到網格布局的效果,首先能夠考慮使用最常見的LinearLayout布局,可是這種排布會產生例如以下幾點問題:
1、不能同一時候在X,Y軸方向上進行控制項的對齊。
2、當多層布局嵌套時會有效能問題。
3、不能穩定地支援一些支援自由編輯布局的工具。
其次考慮使用表格布局TabelLayout,這樣的方式會把包括的元素以行和列的形式進行排列,每行為一個TableRow對象,也能夠是一個View對象,而在TableRow中還能夠繼續加入其它的控制項,每加入一個子控制項就成為一列。可是使用這樣的布局可能會出現不能將控制項佔領多個行或列的問題,並且渲染速度也不能得到非常好的保證。
android4.0以上版本號碼出現的GridLayout布局攻克了以上問題。GridLayout布局使用虛細線將布局劃分為行、列和單元格,也支援一個控制項在行、列上都有交錯排列。而GridLayout使用的事實上是跟LinearLayout類似的API,僅僅只是是改動了一下相關的標籤而已,所以對於開發人員來說,掌握GridLayout還是非常easy的事情。GridLayout的布局策略簡單分為下面三個部分:
首先它與LinearLayout布局一樣,也分為水平和垂直兩種方式,預設是水平布局,一個控制項挨著一個控制項從左至右依次排列,可是通過指定android:columnCount設定列數的屬性後,控制項會自己主動換行進行排列。還有一方面,對於GridLayout布局中的子控制項,預設依照wrap_content的方式設定其顯示,這僅僅須要在GridLayout布局中顯式聲明就可以。
其次,若要指定某控制項顯示在固定的行或列,僅僅需設定該子控制項的android:layout_row和android:layout_column屬性就可以,可是須要注意:android:layout_row=”0”表示從第一行開始,android:layout_column=”0”表示從第一列開始,這與程式設計語言中一維數組的賦值情況類似。
最後,假設須要設定某控制項跨越多行或多列,僅僅需將該子控制項的android:layout_rowSpan或者layout_columnSpan屬性設定為數值,再設定其layout_gravity屬性為fill就可以,前一個設定表明該控制項跨越的行數或列數,後一個設定表明該控制項填滿所跨越的整行或整列。
利用GridLayout布局編寫的簡易計算機代碼例如以下(注意:僅限於android4.0及以上的版本號碼):
<?xml version="1.0" encoding="utf-8"?><GridLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:rowCount="5" android:columnCount="4" > <Button android:id="@+id/one" android:text="1"/> <Button android:id="@+id/two" android:text="2"/> <Button android:id="@+id/three" android:text="3"/> <Button android:id="@+id/devide" android:text="/"/> <Button android:id="@+id/four" android:text="4"/> <Button android:id="@+id/five" android:text="5"/> <Button android:id="@+id/six" android:text="6"/> <Button android:id="@+id/multiply" android:text="×"/> <Button android:id="@+id/seven" android:text="7"/> <Button android:id="@+id/eight" android:text="8"/> <Button android:id="@+id/nine" android:text="9"/><Button android:id="@+id/minus" android:text="-"/><Button android:id="@+id/zero"android:layout_columnSpan="2"android:layout_gravity="fill" android:text="0"/> <Button android:id="@+id/point" android:text="."/><Button android:id="@+id/plus"android:layout_rowSpan="2"android:layout_gravity="fill" android:text="+"/><Button android:id="@+id/equal"android:layout_columnSpan="3"android:layout_gravity="fill" android:text="="/> </GridLayout>
終於實現的介面例如以下所看到的:
參考資料:http://tech.it168.com/a2011/1122/1277/000001277274.shtml
http://hb.qq.com/a/20111214/000865.htm
淺談android4.0開發之GridLayout布局