GridView的使用是很簡單的,API Demo中有例子,但是要實現復雜的GridView,就需要自定義了。
今天我們要實現如下的效果:
先說它的布局,它是由gridview和grid_item兩部分組成。
main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <GridView xmlns:Android="http://schemas.android.com/apk/res/android"
- android:id="@+id/gridview"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:columnWidth="90dp"
- android:numColumns="auto_fit"
- android:verticalSpacing="10dp"
- android:horizontalSpacing="10dp"
- android:stretchMode="columnWidth"
- android:gravity="center"
- />
grid_item.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent" android:layout_height="fill_parent"
- android:orientation="vertical"
- android:layout_marginTop="5dp"
- >
- <ImageView android:id="@+id/image" android:layout_width="80dip"
- android:layout_height="80dip" android:layout_gravity="center_horizontal">
- </ImageView>
- <TextView android:id="@+id/title" android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:layout_gravity="left"
- android:textSize="16dip"
- android:gravity="left">
- </TextView>
-
- <TextView android:id="@+id/description" android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:layout_gravity="left"
- android:textColor="#938192"
- android:textSize="13dip"
- android:gravity="left"
- >
- </TextView>
- </LinearLayout>
接下來我們要新寫一個繼承自BaseAdapter類的Adapter類,在這裡做grid item的適配。
由於我們每個grid item是一個圖片加兩個文本框,就需要有一個容器類:
GridItem類:
- class GridItem
- {
- private String title;
- private int imageId;
- private String description;
-
- public GridItem()
- {
- super();
- }
-
- public GridItem(String title, int imageId,String time)
- {
- super();
- this.title = title;
- this.imageId = imageId;
- this.description = time;
- }
-
- public String getTime( )
- {
- return description;
- }
-
- public String getTitle()
- {
- return title;
- }
-
- public int getImageId()
- {
- return imageId;
- }
- }
再來個Viewholder
- static class ViewHolder
- {
- public ImageView image;
- public TextView title;
- public TextView time;
- }