当我们需要在屏幕上显示多外元素的时候,我们可以选择GridView,
由于有多个元素,我们就要使用BaseAdapter来存储这些元素。使用起来也很简单。
程序的运行结果如下:
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"
/>
package com.liu;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
public class Gridview 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 v, int position, long id)
{
Toast.makeText(Gridview.this, "你选择了" + (position + 1) + " 号图片", Toast.LENGTH_SHORT).show();
}
});
}
}
ImageAdapter.java代码如下:
package com.liu;
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,
R.drawable.img9,
};
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;
}
}