主Activity
package com.example.mygridview;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
ArrayList myList = new ArrayList();
//生成动态数组,并且转入数据
ArrayList> lstImageItem = new ArrayList>();
for(int i=0;i
{
HashMap map = new HashMap();
map.put("ItemImage", R.drawable.ic_launcher);//添加图像资源的ID
map.put("ItemText", "NO."+String.valueOf(i));//按序号做ItemText
lstImageItem.add(map);
}
//生成适配器的ImageItem <====> 动态数组的元素,两者一一对应
SimpleAdapter saImageItems = new SimpleAdapter(this,
lstImageItem,//数据来源
R.layout.night_item,//night_item的XML实现
//动态数组与ImageItem对应的子项
new String[] {"ItemImage","ItemText"},
//ImageItem的XML文件里面的一个ImageView,两个TextView ID
new int[] {R.id.ItemImage,R.id.ItemText});
//添加并且显示
gridview.setAdapter(saImageItems);
}
}
用到下面的来填充数据进GridView
package com.example.mygridview;
public class MenuItem{
private int name;
private int imgeid;
public MenuItem(int name,int imgeid){
super();
this.name=name;
this.imgeid=imgeid;
}
public int getName(){
return name;
}
public void setName(int name){
this.name=name;
}
public int getImgeid(){
return imgeid;
}
public void setImgeid(int imgeid){
this.imgeid=imgeid;
}
}
package com.example.mygridview;
import java.util.ArrayList;
import java.util.List;
public class Menubuilder {
/**
- @author hu
- arrylist方法
*/
public static List newBuild(){
List menu=new ArrayList();
menu.add(new MenuItem(R.string.hello_world,R.drawable.ph5));
menu.add(new MenuItem (R.string.hello_world,R.drawable.ph4));
return menu;
}
}