效果:
主布局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:layout_width="fill_parent" android:layout_height="150dp" android:src="@drawable/show_view" /> <GridView android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="90dp" android:gravity="center" android:horizontalSpacing="2dp" android:numColumns="3" android:stretchMode="columnWidth" android:verticalSpacing="2dp" /> </LinearLayout>1.Android:numColumns=”auto_fit” //GridView的列数设置为自动
2.android:columnWidth=”90dp ” //每列的宽度,也就是Item的宽度
3.android:stretchMode=”columnWidth”//缩放与列宽大小同步
4.android:verticalSpacing=”10dp” //两行之间的边距
5.android:horizontalSpacing=”10dp” //两列之间的边距
item.xml:(小格里面的布局文件)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:paddingBottom="4dip" android:layout_width="fill_parent" android:gravity="center_horizontal" android:background="#fff" > <LinearLayout android:id="@+id/shoukuan" android:layout_width="70dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="20dp" /> <ImageView android:id="@+id/img_shoukuan" android:layout_width="30dp" android:layout_height="30dp" android:layout_weight="1" android:src="@drawable/ic_launcher"/> <TextView android:layout_width="match_parent" android:layout_height="20dp" /> <TextView android:id="@+id/txt_shoukuan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="O2O收款" android:textColor="#000000" android:textSize="13dp" android:gravity="center"/> </LinearLayout> </RelativeLayout>在主界面初始化并设置适配器
GridView gridView=(GridView) mView.findViewById(R.id.gridview);//初始化 //生成动态数组,并且转入数据 ArrayList<HashMap<String ,Object>> listItemArrayList=new ArrayList<HashMap<String,Object>>(); for(int i=0; i<imageRes.length; i++){ HashMap<String, Object> map=new HashMap<String,Object>(); map.put("itemImage", imageRes[i]); map.put("itemText", name[i]); listItemArrayList.add(map); } //生成适配器的ImageItem 与动态数组的元素相对应 SimpleAdapter saImageItems = new SimpleAdapter(getActivity(), listItemArrayList,//数据来源 R.layout.item,//item的XML //动态数组与ImageItem对应的子项 new String[]{"itemImage", "itemText"}, //ImageItem的XML文件里面的一个ImageView,TextView ID new int[]{R.id.img_shoukuan, R.id.txt_shoukuan}); //添加并且显示 gridView.setAdapter(saImageItems); //添加消息处理 gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(getActivity(),name[position],Toast.LENGTH_LONG).show(); } });欢迎交流 qq:627576236
