Android 4.0新組件:GridLayout詳解,androidgridlayout
在Android 4.0(API 14)中提供了一個全新的組件GridLayout,它繼承自Linearlayout,用於進行網格式的布局。
在某些方面,GridLayout與TableLayout和GridView有相似之處。他的強大之處在於可以指定每一個單元格“橫跨”幾個單元格或者“豎跨”幾個單元格,這一點與html中<table>標籤很類似。
GridLayout的幾個重要屬性:
rowCount:行數
columnCount:列數
GridLayout的子View將可以應用屬性:
layout_rowSpan:縱向跨幾個單元格
layout_columnSpan:橫向跨幾個單元格
同時,GridLayout的子View可以不指定layout_width和layout_height(類似於TableLayout)
使用GridLayout可以很方便的開發出類似計算機的頁面,相比使用LinearLayout簡化了代碼、簡化了嵌套層次、提高了效能,並且自適應效能更好。
:
布局代碼:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="8dp" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:text="計算機" /> <GridLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:rowCount="5" android:columnCount="4" android:layout_margin="4dp"> <Button android:text="C" /> <Button android:text="Del" /> <Button android:text="/" /> <Button android:text="x" /> <Button android:text="7" /> <Button android:text="8" /> <Button android:text="9" /> <Button android:text="-" /> <Button android:text="4" /> <Button android:text="5" /> <Button android:text="6" /> <Button android:text="+" /> <Button android:text="1" /> <Button android:text="2" /> <Button android:text="3" /> <Button android:text="=" android:layout_gravity="fill" android:layout_rowSpan="2" /> <Button android:text="0" android:layout_gravity="fill" android:layout_columnSpan="2" /> <Button android:text="." /> </GridLayout></LinearLayout>