转自:http://blog.sina.com.cn/s/blog_55afbecd0100zlv7.html
1. GridView的xml描述
<?xml version="1.0" encoding="utf-8"?>
<GridView
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:verticalSpacing="10dip"
android:horizontalSpacing="10dip"
android:gravity="center"
android:numColumns="4" >
</GridView>
某些属性描述:
android:numColumns="auto_fit" ,GridView的列数设置为自动
android:columnWidth="90dp",每列的宽度,也就是Item的宽度
android:stretchMode="columnWidth",缩放与列宽大小同步
android:verticalSpacing="10dp",两行之间的边距,如:行一(NO.0~NO.2)与行二(NO.3~NO.5)间距为10dp
android:horizontalSpacing="10dp",两列之间的边距。
2. GridView的子项描述:
grid_item.xml,这个XML跟描述每个gridview子项:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:paddingBottom="4dip" >
<ImageView
android:layout_height="100dip"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:id="@+id/ItemImage">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView01"
android:layout_centerHorizontal="true"
android:layout_below="@+id/ItemImage"
android:id="@+id/ItemText">
</TextView>
</RelativeLayout>
3. Activity中的代码
//Activity.onCreate构建grid
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//setContentView(R.layout.home);
mInflater = LayoutInflater.from(this);
mMyView = mInflater.inflate(R.layout.home, null);
setContentView(mMyView);
mGrid = (GridView) mMyView.findViewById(R.id.gridView1);
//1. 生成动态数组
ArrayList<HashMap<String, Object>> lstGridItem = new ArrayList<HashMap<String, Object>>();
for(int i=0; i<sIconArray.length ;i++)
{
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", sIconArray[i]);//添加图像资源的ID
map.put("ItemText", "NO."+String.valueOf(i));//按序号做ItemText
lstGridItem.add(map);
}
//2. 生成SimpleAdapter适配器
SimpleAdapter saImageItems = new SimpleAdapter(this,
lstGridItem,//数据来源
R.layout.grid_item,//grid_item的XML实现
//map中使用的key值列表
new String[] {"ItemImage", "ItemText"},
//grid_Item.xml文件中每个item的UI元素ID
new int[] {R.id.ItemImage, R.id.ItemText});
mGrid.setAdapter(saImageItems);
//3. 设置listener
mGrid.setOnItemClickListener(new ItemClickListener());
}
//当AdapterView被单击(触摸屏或者键盘),则返回的Item单击事件
class ItemClickListener implements OnItemClickListener
{
public void onItemClick(AdapterView<?> arg0,//The AdapterView where the click happened
View arg1,//The view within the AdapterView that was clicked
int arg2,//The position of the view in the adapter
long arg3//The row id of the item that was clicked
) {
//在本例中arg2=arg3
HashMap<String, Object> item=(HashMap<String, Object>) arg0.getItemAtPosition(arg2);
//显示所选Item的ItemText
setTitle((String)item.get("ItemText"));
}
}