GridView的视图排列方式与矩阵类似,当屏幕上有很多元素(文字、图片或其他元素)需要显示时,可以使用GirdView。既然有多个元素要显示,就需要使用BaseAdapter来存储这些元素。用户可能会选择其中一个元素进行操作,这就需要设置事件监听 setOnItemClickListener来捕捉和处理事件。 我们先来看看运行效果吧。
ImageAdapter类
package xiaohang.zhimeng;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter{
//定义Context
private Context mContext;
//定义整型数组 即图片源
private Integer[] mImageIds =
{
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4,
R.drawable.img5,
R.drawable.img6,
R.drawable.img7,
R.drawable.img8,
};
public ImageAdapter(Context c){
mContext = c;
}
//获取图片个数
public int getCount() {
return mImageIds.length;
}
//获取图片在库中的位置
public Object getItem(int position) {
return position;
}
//获取图片ID
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null ) {
//给ImageView设置资源
imageView = new ImageView(mContext);
//设置布局 图片120*120显示
imageView.setLayoutParams(new GridView.LayoutParams(85,85));
//设置显示比例类型
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
}
else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mImageIds[position]);
return imageView;
}
}
Activity类
package xiaohang.zhimeng;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Activity01 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取GridView对象
GridView gridview = (GridView) findViewById(R.id.gridview);
//添加元素给gridview
gridview.setAdapter(new ImageAdapter(this));
//设置Gallery背景
gridview.setBackgroundResource(R.drawable.bg0);
//事件监听
gridview.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//此处的position为ID 所以要+1
Toast.makeText(Activity01.this, "你选择了"+ (position + 1) + "号图片", Toast.LENGTH_SHORT).show();
}
});
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
>
<!--
属性说明
android:numColumns="auto_fit" GridView的列数设置为自动
android:columnWidth="90dp",每列的宽度,也就是Item的宽度
android:stretMode="columnWidth" 缩放与列宽大小同步
android:verticalSpacing="10dp" 两行之间的边距
android:horizontalSpacing="10dp" 两列之间的边距
-->
</GridView>
源码和图片 见附件