package com.example.gridviewdemo; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.view.Menu; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SimpleAdapter; public class MainActivity extends Activity { private GridView gd; private List<Map<String, Integer>> list = new ArrayList<Map<String, Integer>>(); private SimpleAdapter sa; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gd = (GridView) findViewById(R.id.gd); Field[] fieds = R.drawable.class.getDeclaredFields();//利用反射得到图片 for (int i = 0; i < fieds.length; i++) { Map<String, Integer> map = new HashMap<String, Integer>(); try { if(fieds[i].getName().startsWith("pic"))//判断图片开头是不是pic map.put("img", fieds[i].getInt(R.drawable.class));//放进map里 } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } list.add(map); } sa = new SimpleAdapter(MainActivity.this, list, R.layout.grid_layout, new String[] { "img" }, new int[] { R.id.img }); gd.setAdapter(sa); //给网格视图设置点击事件 gd.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ImageView showImg = new ImageView(MainActivity.this); Map<String, Integer> map1 = (Map<String, Integer>) sa .getItem(position); showImg.setImageResource(map1.get("img")); //设置图片大小 showImg.setLayoutParams(new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); //把这个图片用对话框显示出来 new AlertDialog.Builder(MainActivity.this) .setTitle("选择的图片是") .setView(showImg) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
时间: 2024-10-22 12:56:06