網頁

2011年9月15日 星期四

Android學習_GridView的使用

在使用者介面的安排上,我們常常會使用ListView來展示多組資料,就像下圖的感覺:

但有時候,我們要呈現的項目並不是這麼的寬,可能只是一些簡單的文字或是小圖片,而我們希望他們以格子的方式排列,這時候通常就會想到GridView這類的控制項。

之前操作ListView時,通常都會先定義一個表示"每一列"的layout檔案,來產生出不同風格的列表樣式;在GridView也是一樣,我們可以先定義一個layout來表示"每一格"的樣式:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<TextView
android:id="@+id/lab_MItemType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
<TextView
android:id="@+id/lab_MoneyBroupType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>

上面的程式碼表示呈現出GridView中的每一格都有兩個TextView可以放值,而且兩個TextView是呈現垂直排列。

除了定義自己的layout以外,我們必須在要呈現出GridView的Activity的layout上擺上一個GridView標籤:

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview_type"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="7"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>

有幾個GridView獨特的變數紀錄一下
1. android:numColumns:表示每一橫列要展示的個數(若設為auto_fit,似乎就是一行三個)
2. android:verticalSpacing:行跟行中間的間距
3. android:horizontalSpacing:列跟列中間的間距
4. android:columnWidth:每一格的寬度
5. android:stretchMode:格子拉伸模式(none:不要伸縮、spacingWidth:拉伸每列的間距、columnWidth:拉伸每格、spacingWidthUniform:均勻拉伸間距)

呈現出來的效果就像圖中紅框部分:


而要將資料放入的方法,還是應先將資料放入Adapter,再利用setAdapter的方法將資料置入。
可以參考以下三篇:
一維陣列:Android學習_ArrayAdapter的使用
自行處理的二維陣列:Android學習_SimpleAdapter的使用
Cursor的處理:Android學習_SimpleCursorAdapter的使用

沒有留言:

張貼留言