GridView实现九宫格

来源:互联网 发布:票务网站源码 编辑:程序博客网 时间:2024/05/16 13:05

先在layout文件夹中新建一个item.xml,作为九宫格的样式文件

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    android:background="#ffffff"    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_height="wrap_content"    android:paddingBottom="1dp" android:layout_width="fill_parent"    android:gravity="center_horizontal">    <LinearLayout        android:id="@+id/shoukuan"        android:layout_width="70dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:gravity="center"        android:orientation="vertical">        <ImageView            android:layout_marginTop="10dp"            android:id="@+id/img_shoukuan"            android:layout_width="43dp"            android:layout_height="43dp"            android:layout_weight="1"            android:src="@drawable/qb"/>        <TextView            android:layout_marginBottom="10dp"            android:id="@+id/txt_shoukuan"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="文字"            android:textColor="#000000"            android:textSize="13dp"            android:gravity="center"/>    </LinearLayout></RelativeLayout>


然后在java代码中

private String[] name3 = {        "火车票机票",        "滴滴出行",        "京东优选",        "美团外卖",        "电影演出赛事",        "吃喝玩乐",        "酒店",        "蘑菇街女装",        "58到家"};private int[] imageRes3 = {        R.drawable.qb,        R.drawable.qb,        R.drawable.qb,        R.drawable.qb,        R.drawable.qb,        R.drawable.qb,        R.drawable.qb,        R.drawable.qb,        R.drawable.qb};


GridView gridview3 = (GridView) findViewById(R.id.gridview3);int length3 = imageRes3.length;


ArrayList<HashMap<String, Object>> lstImageItem3 = new ArrayList<HashMap<String, Object>>();for (int i = 0; i < length3; i++) {    HashMap<String, Object> map = new HashMap<String, Object>();    map.put("ItemImage", imageRes3[i]);    map.put("ItemText", name3[i]);    lstImageItem3.add(map);}SimpleAdapter saImageItems3 = new SimpleAdapter(this,        lstImageItem3,        R.layout.item,        new String[]{"ItemImage", "ItemText"},        new int[]{R.id.img_shoukuan, R.id.txt_shoukuan});gridview3.setAdapter(saImageItems3);

最后在布局中插入GridView

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">    <GridView        android:id="@+id/gridview"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:columnWidth="90dp"        android:gravity="center"        android:horizontalSpacing="1dp"        android:numColumns="3"        android:stretchMode="columnWidth"        android:verticalSpacing="1dp" /></LinearLayout>

最终实现效果: