GridView是网格形势布局的一种View,要实现它就要设置它的Adapter,GridView的Adapter都是ListAdapter的子类或者间接子类.Adapter其实是起桥接作用的,它把你想要显示的资源放入你指定的组件里面,然后自动地添加进GridView里面。
ListAdapter的父子关系:
现在的例子是:将数张图片资源放进项目的res/drawable里面,将这些图片显示在GridView中,当点击图片的时候会以Toast提醒用户所选图片的ID号.
程序运行结果:
main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <GridView android:id="@+id/myphoto" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="90dp" android:horizontalSpacing="10dp" android:numColumns="3" android:verticalSpacing="10dp" > </GridView> </LinearLayout>
GridViewDemo.java:
public class GridViewDemo extends Activity { private GridView gridView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); gridView = (GridView) findViewById(R.id.myphoto); gridView.setAdapter(new ImageAdapter(this)); gridView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(GridViewDemo.this, "当前被点击的图片ID是:" + position, Toast.LENGTH_SHORT).show(); } }); } /** * 自定义的适配器,用来桥接GridView和需要显示的数据 */ class ImageAdapter extends BaseAdapter { private Context context; // 图片对应的资源ID private List<Integer> imgID; ImageAdapter(Context context) { this.context = context; this.imgID = new ArrayList<Integer>(); // 利用反射机制得到R.drawable类里面的属性,即为图片资源ID Field[] field = R.drawable.class.getDeclaredFields(); for (Field myfield : field) { // 除去程序启动图标 if (!"icon_lunch".equals(myfield.getName())) try { // 得到属性值 Integer index = myfield.getInt(R.drawable.class); imgID.add(index); } catch (Exception e) { e.printStackTrace(); } } // imgID.add(R.drawable.sample_0); // imgID.add(R.drawable.sample_1); // imgID.add(R.drawable.sample_10); // imgID.add(R.drawable.sample_11); // imgID.add(R.drawable.sample_12); // imgID.add(R.drawable.sample_2); // imgID.add(R.drawable.sample_3); } public int getCount() { return imgID.size(); } public Object getItem(int position) { // TODO Auto-generated method stub return null; } public long getItemId(int position) { // TODO Auto-generated method stub return position; } /** * 将对应的资源封装到你定义的组件里,这里是ImageView */ public View getView(int position, View convertView, ViewGroup parent) { ImageView imgView; // 首先判断是否已经存在ImageView,防止重复加载 if (null == convertView) { imgView = new ImageView(context); imgView.setScaleType(ImageView.ScaleType.CENTER_CROP); imgView.setLayoutParams(new GridView.LayoutParams(100, 100)); imgView.setPadding(8, 8, 8, 8); } else imgView = (ImageView) convertView; imgView.setImageResource(imgID.get(position)); return imgView; } } }
关键就在于实现自己的Adapter