首页 > 代码库 > android开发步步为营之35:GridView的用法

android开发步步为营之35:GridView的用法

        之前使用asp.net开发软件的过程中也使用GridView,发现android里面也有这么一个控件,使用方法有点相似,都是使用适配器将数据绑定到这个控件,然后将数据展示出来,应该说它和ListView一样,是个非常常用的控件,所以我们应该学习如何使用它,理论知识是没多少的,就是一个展示数据的控件,继承关系如下:
public class GridView
extends AbsListView
java.lang.Object
   android.view.View
     android.view.ViewGroup
       android.widget.AdapterView<T extends android.widget.Adapter>
         android.widget.AbsListView
           android.widget.GridView
         开始我们的范例:
本范例,我们要实现两种效果:
第一种显示小狗的图片列表,点击图片后触发一个提示消息
第二种显示水浒梁山好汉的头像、姓名、年龄信息,点击一行后会在title显示姓名
第一步、设计页面
res\layout\gridview.xml
 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
    <GridView android:id="@+id/mygridview" android:layout_width="fill_parent"
       android:layout_height="fill_parent" android:columnWidth="90dp"
       android:numColumns="auto_fit" android:horizontalSpacing="10dp"
       android:verticalSpacing="10dp" android:stretchMode="columnWidth"
       android:gravity="center">
    </GridView>
</RelativeLayout>
 
res\layout\personview.xml
 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
    <ImageView android:id="@+id/imgHead" android:layout_width="wrap_content" android:src=http://www.mamicode.com/"@drawable/icon" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true">
    <TextView android:id="@+id/tvName" android:text="姓名" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/imgHead" android:layout_toRightOf="@+id/imgHead" android:layout_marginLeft="40dp" android:layout_marginBottom="14dp"></TextView>
    <TextView android:id="@+id/tvAge" android:text="年龄" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/tvName" android:layout_toRightOf="@+id/tvName" android:layout_marginLeft="68dp"></TextView>
</RelativeLayout>
 
 
第二步、设计Activity  GridViewActivity.java
 
 
/**
 * gridview的用法
 */
package com.figo.helloworld;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
 
/**
 * @author zhuzhifei
 *
 */
public class GridViewActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.gridview);
       //给gv装配数据
       GridView gridView = (GridView) findViewById(R.id.mygridview);
       //使用系统视图ImageView
//     gridView.setAdapter(new ImageAdapter(this));
//     gridView.setColumnWidth(90);
//      // 添加点击行事件
//     gridView.setOnItemClickListener(new OnItemClickListener() {
//     @Override
//     public void onItemClick(AdapterView parent, View view,
//            int position, long id) {
//         Toast.makeText(GridViewActivity.this, "dog"+id+"汪汪汪",
//                Toast.LENGTH_SHORT).show();
//   
//     }
//  });
       //使用简单适配器显示图片+文字
        SimpleAdapter adapter = getSimpleAdapter(); 
        gridView.setAdapter(adapter); 
       gridView.setColumnWidth(200);
        // 添加点击行事件
        gridView.setOnItemClickListener(new OnItemClickListener() { 
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) { 
                // 在本例中arg2=arg3 
                Map<String, Object> item = (Map<String, Object>) parent.getItemAtPosition(position); 
                // 显示所选Item的ItemText 
                setTitle(item.get("name").toString()); 
            } 
        }); 
 
 
    }
  
     /**
     * 简单适配器   显示图片+文字
     * 
     * @return
     */
    private SimpleAdapter getSimpleAdapter() { 
        // 生成动态数组,并且转入数据 
      List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", "宋江");
            map.put("age", "33岁");
            map.put("img", R.drawable.icon);
            list.add(map);
            map = new HashMap<String, Object>();
            map.put("name", "卢俊义");
            map.put("age", "32岁");
            map.put("img", R.drawable.icon);
            list.add(map);
            map = new HashMap<String, Object>();
            map.put("name", "关胜");
            map.put("age", "28岁");
            map.put("img", R.drawable.icon);
            list.add(map);    
            map = new HashMap<String, Object>();
            map.put("name", "林冲");
            map.put("age", "30岁");
            map.put("img", R.drawable.icon);
            list.add(map);
            map.put("name", "吴用");
            map.put("age", "33岁");
            map.put("img", R.drawable.icon);
            list.add(map);
            map = new HashMap<String, Object>();
            map.put("name", "武松");
            map.put("age", "32岁");
            map.put("img", R.drawable.icon);
            list.add(map);
            map = new HashMap<String, Object>();
            map.put("name", "公孙胜");
            map.put("age", "28岁");
            map.put("img", R.drawable.icon);
            list.add(map);    
            map = new HashMap<String, Object>();
            map.put("name", "花荣");
            map.put("age", "30岁");
            map.put("img", R.drawable.icon);
            list.add(map);
 
        // 生成适配器 
        SimpleAdapter adapter = new SimpleAdapter(this, list, 
                R.layout.personview, new String[] { "img", 
                       "name","age" }, new int[] { R.id.imgHead, 
                        R.id.tvName,R.id.tvAge }); 
 
        return adapter; 
    } 
    //图片适配器
    private class ImageAdapter extends BaseAdapter {
       private Context mContext;
       private LayoutInflater mInflater;
       private List<Map<String, Object>> mData;
       // 狗狗图片id集合
       private Integer[] mDogs = { R.drawable.doga, R.drawable.dogb,
              R.drawable.dogc, R.drawable.dogz, R.drawable.dogf, R.drawable.dogr,
              R.drawable.dogl, R.drawable.dogv, R.drawable.dogu,
              R.drawable.dogj,R.drawable.dogk,R.drawable.dogm,
              R.drawable.dogo,R.drawable.dogs,R.drawable.dogw
       };
       public ImageAdapter(Context context) {
           this.mContext = context;
       }
 
       @Override
       public int getCount() {
           return mDogs.length;
       }
 
       @Override
       public Object getItem(int position) {
         
       return mDogs[position];
       }
 
       @Override
       public long getItemId(int position) {
           return position;
       }
 
       @Override
       public View getView(int position, View convertView, ViewGroup parent) {
 
           //使用图片 其实这里也可以使用TextView
           ImageView imageView;
           if (convertView == null) {
              imageView = new ImageView(mContext);
              imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
              imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
              imageView.setPadding(8, 8, 8, 8);
           } else {
              imageView = (ImageView) convertView;
           }
           imageView.setImageResource(mDogs[position]);
           return imageView;
         
         
       }
    }
 
 
}
第四步、运行效果

 

android开发步步为营之35:GridView的用法