Android的GridView一般翻译为网格视图,GridView的排列方式与矩阵类似,用于在界面上按行、列分布的方式来显示多个组件。通过查看GridView类的继承关系,我们发现GridView与ListView有相同的父类:AbsListView,所以GridView与ListView用法有一定的相似性。我们知道ListView只是在一个方面上的分布,而GridView则会在两个方向上分布。同样,GridView也需要通过Adapter知配器来提供显示的数据,我们既可通过SimpleAdapter来为GridView提供数据,也可以通过继续BaseAdapter来为GridView提供数据。
GridView常用的XMl属性如下:
android:columnWidth:设置列的宽度
android:horizontalSpacing:设置各元素之间的水平间距
android:numColumns:设置列数
android:verticalSpacing:设置各元素之间的垂直间距。
下面的这个例子中我们只是简单的演示了GridView的使用,通过SimpleAdapter使用GridView简单的显示一组图片。由于代码都比较熟悉,没有过多的注释。
GridViewDemoActivity.java:
1 |
package com.liuzhichao.gridview; |
3 |
import java.util.ArrayList; |
4 |
import java.util.HashMap; |
8 |
import android.app.Activity; |
9 |
import android.os.Bundle; |
10 |
import android.widget.GridView; |
11 |
import android.widget.SimpleAdapter; |
13 |
public class GridViewDemoActivity extends Activity { |
17 |
static final int [] imgs = new int [] {R.drawable.ringvibrosoundicon,R.drawable.brightnessicon, |
18 |
R.drawable.lockpattern,R.drawable.wifiicon, |
19 |
R.drawable.gpsicon,R.drawable.bluetoothicon, |
20 |
R.drawable.autosync,R.drawable.autorotate, |
21 |
R.drawable.screentimeouticon,R.drawable.airplaneicon, |
22 |
R.drawable.wirelessicon,R.drawable.net2g3gicon}; |
23 |
List<Map<String, Object>> listItems; |
24 |
SimpleAdapter adapter; |
26 |
public void onCreate(Bundle savedInstanceState) { |
27 |
super .onCreate(savedInstanceState); |
28 |
setContentView(R.layout.main); |
29 |
gridView = (GridView)findViewById(R.id.gridView1); |
32 |
listItems = new ArrayList<Map<String,Object>>(); |
33 |
for ( int i = 0 ; i < imgs.length; i++) { |
34 |
Map<String, Object> map = new HashMap<String, Object>(); |
35 |
map.put( "img" , imgs[i]); |
39 |
adapter = new SimpleAdapter( this , listItems, R.layout.image, new String[]{ "img" }, new int []{}); |
40 |
gridView.setAdapter( adapter); |
使用到的image.xml布局文件:
<? xml version = "1.0" encoding = "utf-8" ?> |
android:layout_width = "fill_parent" |
android:layout_height = "fill_parent" |
android:orientation = "vertical" > |
android:layout_width = "wrap_content" |
android:layout_height = "wrap_content" > |
主布局文件main.xml:
1 |
<? xml version = "1.0" encoding = "utf-8" ?> |
3 |
android:layout_width = "fill_parent" |
4 |
android:layout_height = "fill_parent" |
5 |
android:orientation = "vertical" > |
8 |
android:id = "@+id/gridView1" |
9 |
android:numColumns = "auto_fit" |
10 |
android:gravity = "center" |
11 |
android:columnWidth = "100dp" |
12 |
android:stretchMode = "columnWidth" |
13 |
android:layout_width = "fill_parent" |
14 |
android:layout_height = "fill_parent" > |
运行效果: