Android 4.0新組件:GridLayout詳解

ybw8 9年前發布 | 17K 次閱讀 Android Android開發 移動開發

在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=" 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>  </pre><br />
 本文由用戶 ybw8 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!