public class GridViewFunction extends Activity {
private GridView _gridview;
private List<Map<String ,Object>> list;
_gridview=(GridView) findViewById(R.id.gridView1);
list=new ArrayList<Map<String,Object>>();
for (int i = 0; i < 9; i++) {
Map<String,Object> map=new HashMap<String, Object>();
map.put("img",R.drawable.icon);
map.put("text",i+"item");
list.add(map);
}
SimpleAdapter simple=new SimpleAdapter(getApplicationContext(), list, R.layout.gridview_item,new String[]
{"img","text"},new int[]{R.id.log_item_image,R.id.log_item_text}); _gridview.setAdapter(new GridViewAdapter(this));
}
R.layout.gridview_item 文件里面放2个。一个图片和一个文字:
主文件直接放GIRDVIEW控件。
<GridView android:id="@+id/gridView1"
android:layout_width="fill_parent"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:columnWidth="90dp"
android:gravity="center"
android:layout_height="fill_parent">
</GridView>
这样就完成了。
当然,如果简单一点的话直接适配比较好!
代码以下:
class GridViewAdapter extends BaseAdapter{
private Context ct;
public GridViewAdapter(Context ct){
this.ct=ct;
}
private int [] img={R.drawable.imagebutton1,R.drawable.imagebutton2,R.drawable.imagebutton3,
R.drawable.imagebutton4,R.drawable.imagebutton5,R.drawable.imagebutton6,R.drawable.imagebutton7,R.drawable.imagebutton8,R.drawable.imagebutton9};
private String [] text= {
"A","B","C","D"
,"E","F","G","H"
,"I"
};
@Override
public int getCount() {
// TODO Auto-generated method stub
return text.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
WrapperImgText wrapper;
if(convertView==null){
wrapper=new WrapperImgText();
LayoutInflater layout=LayoutInflater.from(ct);
convertView=layout.inflate(R.layout.gridview_item,null);
convertView.setTag(wrapper);
convertView.setPadding(15, 15, 15, 15);
}else{
wrapper=(WrapperImgText) convertView.getTag();
}
wrapper.image=(ImageView) convertView.findViewById(R.id.log_item_image);
wrapper.tv=(TextView) convertView.findViewById(R.id.log_item_text);
wrapper.image.setBackgroundResource(img[position]);
wrapper.tv.setText(text[position]);
return convertView;
}
class WrapperImgText{
ImageView image;
TextView tv;
}
}