我有以下代码用于在我的android网格视图中显示几个url图像。问题是,在网格视图中显示少量图像需要花费大量时间。这些是我的代码:
public class GridViewImageAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> galleryAttributes = new ArrayList<HashMap<String, String>>();
private int imageWidth;
int ctr = 0;
public GridViewImageAdapter(Activity activity,
ArrayList<HashMap<String, String>> galleryAttributes, int imageWidth) {
this.activity = activity;
this.galleryAttributes = galleryAttributes;
this.imageWidth = imageWidth;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return galleryAttributes.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return galleryAttributes.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView;
if(convertView == null){
imageView = new ImageView(activity);
}else{
imageView = (ImageView) convertView;
}
LoadImage loadImage = new LoadImage();
try {
Bitmap image = loadImage.execute(galleryAttributes.get(position).get("Link")).get();
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
imageView.setImageBitmap(image);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imageView;
}
public class LoadImage extends AsyncTask<String, String, Bitmap>{
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
try{
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream((InputStream) new URL(params[0]).getContent(), null, o);
final int REQUIRED_WIDTH = imageWidth;
final int REQUIRED_HEIGHT = imageWidth;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HEIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream((InputStream) new URL(params[0]).getContent(), null, o2);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
答案 0 :(得分:0)
尝试使用毕加索
http://square.github.io/picasso/
这个库将缓存从URL下载的图片,下次打开它时,它会加载得更快,因为你不需要再次下载它,只需从缓存中取出它。
如果初始显示也很慢,请尝试将其调整为合理的大小。
用法也很简单:
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
答案 1 :(得分:0)
您可以使用Glide或Picasso。 但Glide也有缩略图支持。
Glide.with(本) .load(galleryAttributes.get(位置)获得( “链接”)) .thumbnail(0.1F) .into(ImageView的);
Picasso.with(本).load(galleryAttributes.get(位置)获得( “链接”))代入(ImageView的)。