xml布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"源代码
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#55FFFF"
>
<GridView
android:id="@+id/gridview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="30dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="30dp" />
</RelativeLayout>
package com.example.gridview;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;
/**
*
* @author TXF
*
* GridView(网格视图,适配器和Gallery的适配器是一样的)
*
*/
public class MainActivity extends Activity {
private GridView mgv;
private Context mcontext;
private Integer[] imageIds = { R.drawable.a, R.drawable.b, R.drawable.c,
R.drawable.d, R.drawable.e };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mgv = (GridView) findViewById(R.id.gridview);
// 设置GridView的背景
// mgv.setBackgroundColor(Color.BLUE);
// 设置GridView的条目事件监听
mgv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
Toast.makeText(MainActivity.this,
"您选择了" + (position + 1) + "号图片", 0).show();
}
});
// 设置适配器和Gallery的适配器是一样的,都是自定义适配器
mgv.setAdapter(new MyAdapter(this));
}
private class MyAdapter extends BaseAdapter {
public MyAdapter(Context c) {
mcontext = c;
}
@Override
public int getCount() {
return imageIds.length;
}
@Override
public Object getItem(int position) {
return imageIds[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView iv = new ImageView(mcontext);
// 设置图片资源
iv.setImageResource(imageIds[arg0]);
// 设置布局图片的比例以90*90显示(宽高)
iv.setLayoutParams(new GridView.LayoutParams(90, 90));
// 设置图片显示的比例类型
iv.setScaleType(ImageView.ScaleType.CENTER);
// 返回图片
return iv;
}
}
}
效果图