先看效果:
请先准备好一些图片,放在资源文件夹中res/drawable-hdpi
第一步:
在您的布局文件中添加一个组件GridView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3"
>
</GridView>
</LinearLayout>
numColumns="3" 设置每一行显示的个数
第二步:再次创建一个布局文件,布局格式为线性布局,方向为垂直方向,因为等一下我们上面显示图片下面显示文字说明,说以利用线下布局
然后在该布局文件中,添加两个组件,一个是ImageView 一个是TextView,分别添加id名为iamge 和text,这就是等一下用来显示图片和文字的。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="70dp"
android:layout_gravity="center_horizontal"
/>
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"/>
</LinearLayout>
当然,这里的宽高和对齐方式自己调整。
第三步:在activity中,得到GridView,然后绑定适配器,这里的SimpleAdapter比较难理解,下面的代码有详细说明
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.second_activity);
// 得到网格视图
GridView gridView =(GridView) this.findViewById(R.id.gridView);
//定义适配器
//参数1:上下文
//参数2:数据,数据必须是list(及其子类),而且list中必须放的hashmap对象
//如果图片下面需要显示文字,那么一个hashmap对象就需要存入两个值,一个是图片,一个是文字说明
//这样一个hashmap就描述显示了一个图片,图片可以直接传入图片的id
//参数3:这每个图片和图片的文字为一个单元,这每个单元放在哪个布局文件中,因为可能有多张
//图片,所以会使用多次
//参数4:图片和显示文字的key是什么,
//参数5:to表示显示的视图组件的ID
ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
int[] imageint =new int[6];
imageint[0]=R.drawable.image1;
imageint[1]=R.drawable.image2;
imageint[2]=R.drawable.image3;
imageint[3]=R.drawable.image4;
imageint[4]=R.drawable.image5;
imageint[5]=R.drawable.image6;
for(int i=0;i<=5;i++){
HashMap<String, Object> hash = new HashMap<String, Object>();
hash.put("image",imageint[i]);
hash.put("text", "image"+i);
data.add(hash);
}
String[] form = {"image","text"};
int[] to =new int [2];
to[0]=R.id.image;
to[1]=R.id.text;
SimpleAdapter simpleadapter = new SimpleAdapter(this, data, R.layout.griditemlayout, form, to);
gridView.setAdapter(simpleadapter);
}
说明,这里的SimpleAdapter参数可能看不懂,但是根据代码可以看出他们的具体含义。
需要注意的是:
所有数据放在list中,而list中的数据又是hashmap对象,每个hashmap对象描述一个图片,这里直接传入了R文件图片的id,然后在ImageView中就显示了图片,具体原因不知道,但是这样写确实显示了图片。