基于BaseAdapter的GridView设置ImageView大小
网上找了好多,都是基于SimpleAdapter的,本身在Item.xml中就对ImageView设置了id,而基于BaseAdapter的几乎没有,搞了好长时间一直有问题,这里参考网友的一篇文章(http://www.cnblogs.com/over140/archive/2010/09/14/1825649.html),成功实现了这一功能。
public View getView(int position, View subView, ViewGroup viewGroup) {
ImageView imageView;
if(subView ==null)
{
imageView = new ImageView(GridViewActivity.this);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//设置ImageView高度
GridView.LayoutParams params = new GridView.LayoutParams(LayoutParams.MATCH_PARENT,screenWidth/4); //(1)
imageView.setLayoutParams(params);
}else{
imageView = (ImageView) subView;
}
Bitmap bm = BitmapFactory.decodeFile("sdcard/PictureTrans/"+MainActivity.username+"/thumbnails/"+MainActivity.localImgList[position]);
imageView.setImageBitmap(bm);
return imageView;
}
这里一定要注意语句(1)中为GridView.LayoutParams。否则会报错。
原因:LayoutParams导包时导的是android.view.ViewGroup.LayoutParams包;如果直接用
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,screenWidth/4);
则在获取LayoutParams时内部是将这个属性转到android.widget.AbsListView.LayoutParams,也就是这里setLayoutParams弄错了,故这里需要使用GridView.LayoutParam。