Android之GridLayout用法

本文重點講述了自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及以上的版本):

  1. <?xmlversion="1.0"encoding="utf-8"?>

  2. <GridLayoutxmlns:android="http://schemas.android.com/apk/res/android"

  3. android:layout_width="wrap_content"

  4. android:layout_height="wrap_content"

  5. android:orientation="horizontal"

  6. android:rowCount="5"

  7. android:columnCount="4">

  8. <Button

  9. android:id="@+id/one"

  10. android:text="1"/>

  11. <Button

  12. android:id="@+id/two"

  13. android:text="2"/>

  14. <Button

  15. android:id="@+id/three"

  16. android:text="3"/>

  17. <Button

  18. android:id="@+id/devide"

  19. android:text="/"/>

  20. <Button

  21. android:id="@+id/four"

  22. android:text="4"/>

  23. <Button

  24. android:id="@+id/five"

  25. android:text="5"/>

  26. <Button

  27. android:id="@+id/six"

  28. android:text="6"/>

  29. <Button

  30. android:id="@+id/multiply"

  31. android:text="×"/>

  32. <Button

  33. android:id="@+id/seven"

  34. android:text="7"/>

  35. <Button

  36. android:id="@+id/eight"

  37. android:text="8"/>

  38. <Button

  39. android:id="@+id/nine"

  40. android:text="9"/>

  41. <Button

  42. android:id="@+id/minus"

  43. android:text="-"/>

  44. <Button

  45. android:id="@+id/zero"

  46. android:layout_columnSpan="2"

  47. android:layout_gravity="fill"

  48. android:text="0"/>

  49. <Button

  50. android:id="@+id/point"

  51. android:text="."/>

  52. <Button

  53. android:id="@+id/plus"

  54. android:layout_rowSpan="2"

  55. android:layout_gravity="fill"

  56. android:text="+"/>

  57. <Button

  58. android:id="@+id/equal"

  59. android:layout_columnSpan="3"

  60. android:layout_gravity="fill"

  61. android:text="="/>

  62. </GridLayout>




最終實現的界面如下所示:

14185541_kfBi.gif


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章