本文重點講述了自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還是很容易的事情。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及以上的版本):
<?xmlversion="1.0"encoding="utf-8"?>
<GridLayoutxmlns: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>
最終實現的界面如下所示: