Android GridLayout(網(wǎng)格布局)

2023-03-31 13:37 更新

本節(jié)引言

今天要介紹的布局是 Android 4.0 以后引入的一個新的布局,和前面所學的 TableLayout (表格布局) 有點類似,不過他有很多前者沒有的東西,也更加好用,

  • 可以自己設置布局中組件的排列方式
  • 可以自定義網(wǎng)格布局有多少行,多少列
  • 可以直接設置組件位于某行某列
  • 可以設置組件橫跨幾行或者幾列

另外,除了上述內(nèi)容外,本節(jié)還會給大家使用 gridLayout 時會遇到的問題,以及如何解決低版本 sdk 如何使用   GridLayout 的方法!接下來就開始本節(jié)的課程吧!


1.相關(guān)屬性總結(jié)圖


2.使用實例:計算器布局的實現(xiàn):

運行效果圖:

實現(xiàn)代碼:

<pre>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/GridLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:columnCount="4"
    android:orientation="horizontal"
    android:rowCount="6" >

    <TextView
        android:layout_columnSpan="4"
        android:layout_gravity="fill"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:background="#FFCCCC"
        android:text="0"
        android:textSize="50sp" />

    <Button
        android:layout_columnSpan="2"
        android:layout_gravity="fill"
        android:text="回退" />

    <Button
        android:layout_columnSpan="2"
        android:layout_gravity="fill"
        android:text="清空" />

    <Button android:text="+" />

    <Button android:text="1" />

    <Button android:text="2" />

    <Button android:text="3" />

    <Button android:text="-" />

    <Button android:text="4" />

    <Button android:text="5" />

    <Button android:text="6" />

    <Button android:text="*" />

    <Button android:text="7" />

    <Button android:text="8" />

    <Button android:text="9" />

    <Button android:text="/" />

    <Button
        android:layout_width="wrap_content"
        android:text="." />

    <Button android:text="0" />

    <Button android:text="=" />

</GridLayout> 

代碼解析: 代碼很簡單,只是回退與清楚按鈕橫跨兩列,而其他的都是直接添加的,默認每個組件都是 占一行一列,另外還有一點要注意的: 我們通過: android:layout_rowSpan 與 android:layout_columnSpan 設置了組件橫跨 多行或者多列的話,如果你要讓組件填滿橫越過的行或列的話,需要添加下面這個屬性: android:layout_gravity = "fill"?。。【拖襁@個計算機顯示數(shù)字的部分!


3.用法歸納:

①GridLayout 使用虛細線將布局劃分為行,列和單元格,同時也支持在行,列上進行交錯排列 ②使用流程:

  • step 1:先定義組件的對其方式 android:orientation 水平或者豎直,設置多少行與多少列
  • step 2:設置組件所在的行或者列,記得是從0開始算的,不設置默認每個組件占一行一列
  • step 3:設置組件橫跨幾行或者幾列;設置完畢后,需要在設置一個填充:android:layout_gravity = "fill"

4.使用 GridLayout 要注意的地方:

因為 GirdLayout 是 4.0后才推出的,所以 minSDK 版本要改為14或者以上的版本, 不然寫布局代碼的時候,這玩意就會莫名其妙地出錯,說找不到這個 GridLayout, 當然,如果你要低版本兼容的話,就要看下面的內(nèi)容了!


5.低版本 sdk 如何使用 GridLayout:

解決方法很簡單:只需要導入 v7 包的 gridlayout 包即可! v7 包一般在 sdk 下的:sdk\extras\android\support\v7\gridlayout 目錄下 如果你沒有的話,也可以到這里下載: gridlayout_v7_jay.rar 但是用的時候,標簽卻是這樣寫的:

<android.support.v7.widget.GridLayout>`

本節(jié)小結(jié)

關(guān)于 GridLayout 的介紹就到這里~


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號