我有以下代码用于在我的 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;
}
}