GridView网格布局
1./TestGridView/res/layout/main.xml:
1 <?xml version="1.0" encoding="utf-8"?>
2 <GridView xmlns:android="http://schemas.android.com/apk/res/android"
3 android:id="@+id/gridview"
4 android:layout_width="fill_parent"
5 android:layout_height="fill_parent"
6 android:numColumns="auto_fit"
7 android:verticalSpacing="10dp"
8 android:horizontalSpacing="10dp"
9 android:columnWidth="90dp"
10 android:stretchMode="columnWidth"
11 android:gravity="center"
12 />
2. TestGridViewActivity:
1 import android.app.Activity;
2 import android.os.Bundle;
3 import android.view.View;
4 import android.widget.AdapterView;
5 import android.widget.GridView;
6 import android.widget.Toast;
7 import android.widget.AdapterView.OnItemClickListener;
8
9 public class TestGridViewActivity extends Activity {
10 @Override
11 public void onCreate(Bundle savedInstanceState) {
12 super.onCreate(savedInstanceState);
13 setContentView(R.layout.main);
14 GridView gridView = (GridView) findViewById(R.id.gridview);
15 gridView.setAdapter(new ImageAdapter(this));
16 gridView.setBackgroundResource(R.drawable.bg);
17 gridView.setOnItemClickListener(new OnItemClickListener()
18 {
19 @Override
20 public void onItemClick(AdapterView<?> parent, View v, int position, long id)
21 {
22 Toast.makeText(TestGridViewActivity.this, "你选择的是"+(position+1)+"号图片", Toast.LENGTH_SHORT).show();
23 }
24 });
25 }
26 }
3.ImageAdapter:
1 import android.content.Context;
2 import android.view.View;
3 import android.view.ViewGroup;
4 import android.widget.BaseAdapter;
5 import android.widget.Gallery;
6 import android.widget.GridView;
7 import android.widget.ImageView;
8
9 public class ImageAdapter extends BaseAdapter
10 {
11 private Context mContext;
12
13 // 定义整形数组,即图片源
14 private Integer[] mImageId = {R.drawable.imag1, R.drawable.imag2, R.drawable.imag3, R.drawable.imag4,
15 R.drawable.imag5, R.drawable.imag6, R.drawable.imag7, R.drawable.imag8, R.drawable.imag9,
16 R.drawable.imag10, R.drawable.imag11, R.drawable.imag12};
17
18 public ImageAdapter(Context c)
19 {
20 this.mContext = c;
21 }
22
23 // 获取图片的个数
24 @Override
25 public int getCount()
26 {
27 return mImageId.length;
28 }
29
30 // 获取图片在库中的位置
31 @Override
32 public Object getItem(int position)
33 {
34 return position;
35 }
36
37 // 获取图片在库中的位置
38 @Override
39 public long getItemId(int position)
40 {
41 return position;
42 }
43
44 @Override
45 public View getView(int position, View convertView, ViewGroup parent)
46 {
47 ImageView imageView = new ImageView(mContext);
48 // 给ImageView设置资源
49 imageView.setImageResource(mImageId[position]);
50 // 设置布局以10*10显示
51 // imageView.setLayoutParams(new Gallery.LayoutParams(10,10));
52 // 设置显示比例类型
53 imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
54 return imageView;
55 }
56 }
4. 效果图:
软件运行界面
选择里面的一张图片后的效果