<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:numColumns="auto_fit"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:verticalSpacing="1dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
android:numColumns="auto_fit" ,GridView的列数设置为自动
android:columnWidth="90dp",每列的宽度,也就是Item的宽度android:stretchMode="columnWidth",缩放与列宽大小同步
android:verticalSpacing="10dp",两行之间的边距,
android:horizontalSpacing="10dp",两列之间的边距。
public class Z04_19Activity extends Activity {
private Integer[] m_imagelist={R.drawable.img1,R.drawable.img2,
R.drawable.img3,R.drawable.img4,R.drawable.img5};
private Integer[] m_imageid={R.drawable.img1,R.drawable.img2,
R.drawable.img3,R.drawable.img4,R.drawable.img5};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview=(GridView)findViewById(R.id.gridview);
//添加元素给gridview
gridview.setAdapter(new ImageAdapter(this));
//Listener
gridview.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent,View v,int position, long id)
{
Toast.makeText(Z04_19Activity.this, "我"+(position+1), Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter
{
public ImageAdapter(Context c)
{
mContext=c;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return m_imagelist.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageview=new ImageView(mContext);
//给ImageView设置资源
imageview.setImageResource(m_imageid[position]);
//设置布局图片120*120
imageview.setLayoutParams(new GridView.LayoutParams(80,80));
//设置显示比例类型
imageview.setScaleType(ImageView.ScaleType.FIT_CENTER);
return imageview;
}
private Context mContext;
}
}