package xiaosi.gridview;import java.util.ArrayList;import java.util.HashMap;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.GridView;import android.widget.SimpleAdapter;public class GridViewActivity extends Activity { /** Called when the activity is first created. */ private GridView gridview = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GridView gridview = (GridView) findViewById(R.id.gridview); //生成数据源 一个List ArrayList> DateList = new ArrayList >(); for(int i=0;i<15;i++) { //医用HashMap来存储 HashMap hashMap = new HashMap (); //添加图像资源的ID hashMap.put("Image", R.drawable.a); //按序号做ItemText hashMap.put("Text", "NO."+String.valueOf(i)); //添加到List去 DateList.add(hashMap); } //生成适配器的simpleAdapter //DateList 数据源 //R.layout.item 来自于item。xml 控制GridView中每一项的布局(一个ImageView 一个TextView) //第三个参数是hashoMap的键值 //第四个参数是item。xml中ImageView,TextView的ID SimpleAdapter simpleAdapter = new SimpleAdapter(this,DateList,R.layout.item, new String[] {"Image","Text"}, new int[] {R.id.ItemImage,R.id.ItemText}); //添加并且显示 gridview.setAdapter(simpleAdapter); //添加消息处理 gridview.setOnItemClickListener(new ItemClickListener()); } private class ItemClickListener implements OnItemClickListener { public void onItemClick(AdapterView arg0,View arg1, int arg2,long arg3) { //arg0就是那个DateList HashMap item=(HashMap ) arg0.getItemAtPosition(arg2); //显示应用标题的那个TextView setTitle((String)item.get("Text")); } }}
main.xml
创建item.xml