在android中 gridView是用来显示表格数据式的控件,其使用方法和listview基本相同,即要在java程序中获得在cml中定义的gridView控件,利用findviewById()就好。

然后再利用adapter对其进行适配,即gridView.setAdapter(adapter).来适配  主要的就涉及到adapter的使用方法

1、显示数据的时常用simpleadapter();

SimpleAdapter(context, data, resource, from, to)要知道配置其中的参数就可以利用其来配置gridView。


上代码: 

GridView mainGridView = (GridView) menuView.findViewById(R.id.menu_gridview);//获得GridView对象
mainGridView.setAdapter(getAdapter(itemnameStrings, itemimagesources));//适配///下面这个时获得adapter的方法
private SimpleAdapter getAdapter(String[] itemnames,int[] sources){

ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String,Object>>();
for(int i=0;i<itemnames.length;i++){
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("item_image", sources[i]);
map.put("item_text", itemnames[i]);
list.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list, R.layout.item_menu,
new String[]{"item_image","item_text"}, new int[]{R.id.item_image,R.id.item_text});
return adapter;

 }

2、继承baseadapter()


private class GridViewAdapter extends BaseAdapter{
LayoutInflater inflater;
public GridViewAdapter(Context context){
this.inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return packageInfos.size();
}


@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return packageInfos.get(position);
}


@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.grid_view_item, null);
TextView imagetext= (TextView) view.findViewById(R.id.image_text);
ImageView imageview = (ImageView) view.findViewById(R.id.image_item);
//imagetext.setText(packageInfos.get(position).packageName);
imagetext.setText(packageInfos.get(position).applicationInfo.loadLabel(getPackageManager()));//显示的是软件名
imageview.setImageDrawable(packageInfos.get(position).applicationInfo.loadIcon(getPackageManager()));//获取软件包的图片
return view;
}

}