GridView网格布局

1     /TestGridView/res/layout/main.xml:

<?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"
/>

2     TestGridViewActivity:

 

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 TestGridViewActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
gridView.setBackgroundResource(R.drawable.bg);
gridView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Toast.makeText(TestGridViewActivity.this, "你选择的是"+(position+1)+"号图片", Toast.LENGTH_SHORT).show();
}
});
}
}

3 ImageAdapter:

 

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter
{
private Context mContext;

// 定义整形数组,即图片源
private Integer[] mImageId = {R.drawable.imag1, R.drawable.imag2, R.drawable.imag3, R.drawable.imag4,
R.drawable.imag5, R.drawable.imag6, R.drawable.imag7, R.drawable.imag8, R.drawable.imag9,
R.drawable.imag10, R.drawable.imag11, R.drawable.imag12};

public ImageAdapter(Context c)
{
this.mContext = c;
}

// 获取图片的个数
@Override
public int getCount()
{
return mImageId.length;
}

// 获取图片在库中的位置
@Override
public Object getItem(int position)
{
return position;
}

// 获取图片在库中的位置
@Override
public long getItemId(int position)
{
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView = new ImageView(mContext);
// 给ImageView设置资源
imageView.setImageResource(mImageId[position]);
// 设置布局以10*10显示
// imageView.setLayoutParams(new Gallery.LayoutParams(10,10));
// 设置显示比例类型
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
return imageView;
}
}

4.效果图:

                

                          软件运行界面                                                       选择里面的一张图片后的效果




posted @ 2012-01-03 16:09  程序学习笔记  阅读(193)  评论(0编辑  收藏  举报