本文需要添加/修改3个文件:main.xml、meunitem.xml、JAVA源代码。
main.xml源代码如下,本身是个GirdView,用于装载Item:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/GridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"></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",两列之间的边距。
接下来介绍 meunitem.xml,这个XML跟前面ListView的ImageItem.xml很类似:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView android:layout_width="wrap_content"
android:id="@+id/ItemImage"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ItemImage"
android:id="@+id/ItemText"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
最后是JAVA的源代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
GridView gridview = (GridView) findViewById(R.id.GridView);
ArrayList<HashMap<String, Object>> meumList = new ArrayList<HashMap<String, Object>>();
for(int i = 1;i < 10;i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", R.drawable.icon);
map.put("ItemText", "NO."+i);
meumList.add(map);
}
SimpleAdapter saMenuItem = new SimpleAdapter(this,
meumList, //数据源
R.layout.menuitem, //xml实现
new String[]{"ItemImage","ItemText"}, //对应map的Key
new int[]{R.id.ItemImage,R.id.ItemText}); //对应R的Id
//添加Item到网格中
gridview.setAdapter(saMenuItem);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
System.out.println("click index:"+arg2);
}
}
);
}
附上
效果图: