//定义图片整型数组
private int[] mImages={
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4,
R.drawable.img5
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.night_grid);
//实例化GridView
GridView mGridView=(GridView) findViewById(R.id.gridview);
// 生成动态数组,并且传入数据
ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < mImages.length; i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", mImages[i]);// 添加图像资源的ID
map.put("ItemText", "NO." + String.valueOf(i+1));// 按序号做ItemText
lstImageItem.add(map);
}
//构建一个适配器
SimpleAdapter simple = new SimpleAdapter(this, lstImageItem,
R.layout.gridview_item,
new String[] { "ItemImage", "ItemText" }, new int[] {
R.id.ItemImage, R.id.ItemText });
mGridView.setAdapter(simple);
//添加选择项监听事件
mGridView.setOnItemClickListener(new GridView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast toast=Toast.makeText(getApplicationContext(), "你选择了"+(position+1)+"号图片", 1);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.show();
}
});
}
gridview_item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scrollbars="vertical"> <ImageView android:layout_height="100dip" android:id="@+id/ItemImage" android:layout_width="80dip" android:src="@drawable/img1" android:layout_gravity="center_horizontal" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:id="@+id/ItemText" android:text="名称" /> </LinearLayout>
night_grid.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <GridView android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:numColumns="3" /> </LinearLayout>