android组件之GridView

  GridView可以做成图片浏览器,类似九宫格那样,当然也可以配合适配器做出各种的效果,比如activityGroup等。

  今天先配合SimpleAdapter做个图片浏览器,当然也可以通过自定义适配器继承BaseAdapter实现

  先附上效果图:

android组件之GridView_第1张图片

在main.xml中添加 GridView组件



    

创建item.xml配置文件用于定义GridView中选项的样式



    

    


activity中的代码如下:

public class MainActivity extends Activity {
	private GridView view = null;
	private List> list = new ArrayList>();//用于保存GridView中选项的资源
	private int imgRes[] = { R.drawable.car01, R.drawable.car02,
			R.drawable.car03, R.drawable.car04, R.drawable.car05 };
	private String[] title = { "图片01", "图片02", "图片03", "图片04", "图片05" };


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_main);
		this.view = (GridView) this.findViewById(R.id.view);


		for (int i = 0; i < imgRes.length; i++) {//通过循环方式将资源添加到list中
			Map map = new HashMap();
			map.put("pic", String.valueOf(imgRes[i]));
			map.put("title", title[i]);
			list.add(map);
		}
		this.view.setAdapter(new SimpleAdapter(this, MainActivity.this.list,  //添加适配器
				R.layout.item, new String[] { "pic", "title" }, new int[] {
						R.id.img, R.id.title }));
		this.view.setOnItemClickListener(new OnItemClickListenerImpl());
	}


	private class OnItemClickListenerImpl implements OnItemClickListener {//添加选项点击的响应事件


		@Override
		public void onItemClick(AdapterView parent, View view, int position,
				long id) {
			Toast.makeText(MainActivity.this, "你当前选择了第" + position + "张图片",
					Toast.LENGTH_LONG).show();


		}


	}





你可能感兴趣的:(android组件之GridView)