Android 控件系列: GridView 的简单使用

要做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);
	}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值