要做gridview 首先我们要做的有三点:
1. xml中添加 GridView 控件
2. 继承BaseAdapter 类
3. 载入数据到GridView
1. xml 中添加 GridView控件
<GridView
android:id="@+id/GridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="5dip"
android:layout_marginBottom="5dip"
android:gravity="center"
android:columnWidth="42dip"
android:numColumns="auto_fit"
></GridView>
android:columnWidth 该属性表示每个项的宽度
android:numColumns 该属性表示自动排列项
2. 继承BaseAdapter类
public class GridViewAdapter extends BaseAdapter
{
//private ArrayList<Integer> mIndexList;
private ArrayList<Drawable> mDrawables;
private int mWidth;
private int mHeight;
private Context mContext;
public GridViewAdapter(Context context, ArrayList<Drawable> drawables, int width, int height)
{
//mIndexList = indexList;
mDrawables = drawables;
mWidth = width;
mHeight = height;
mContext = context;
}
@Override
public int getCount()
{
// TODO Auto-generated method stub
return mDrawables.size();
}
@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)
{
ImageView img;
if(convertView == null)
{
img = new ImageView(mContext);
img.setScaleType(ImageView.ScaleType.FIT_CENTER);
img.setLayoutParams(new GridView.LayoutParams(mWidth, mHeight));
}
else
{
img = (ImageView)convertView;
}
img.setImageDrawable(mDrawables.get(position));
return img;
}
}
3. 载入数据到GridView
private void addData()
{
ArrayList<Drawable> drawables = new ArrayList<Drawable>();
int nCount = 50; //GridView要放入图标的总数量
for(int i = 0; i < nCount; i++)
{
drawables.add(mContext.getResources().getDrawable(R.drawable.icon));
}
GridViewAdapter gridViewAdapter = new GridViewAdapter(mContext, drawables, 48, 48);
mGridView.setAdapter(gridViewAdapter);
}