我认为最有效的方法是为此使用 AsyncTask 。看一个个人的例子:
public class LoadImage extends AsyncTask<Void, Void, String> {
private LoaderImageView loaderImageView;
private int position;
private ImageView image;
private Bitmap bmd;
public LoadImage(LoaderImageView loaderImageView, int position) {
this.loaderImageView = loaderImageView;
this.position = position;
image = loaderImageView.getImageView();
}
@Override
protected void onPreExecute() {
loaderImageView.showProgress();
super.onPreExecute();
}
private void setImageView(int heigthToSet, int weightToSet, int color) {
// set the imageview to the current bitmap
Bitmap bitmap = null;
ReceiptImageDataSource ds = ReceiptImageDataSource.getInstance();
List<ReceiptImage> images = ds.selectReceiptImagesByReceiptID(currentReceipt.getId());
if (images.size() > 0) {
if (BitmapFactory.decodeFile(images.get(position).getPhotoURL()) != null) {
if (images.size() > position) {
bitmap = BitmapFactory.decodeFile(images.get(position).getPhotoURL());
image.setTag(position);
} else {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.photo_take_photo);
}
} else {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.no_photo_receipt_x2);
}
}
assert bitmap != null;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// calculate the scale - in this case = 0.6f
float scaleWidth = ((float) weightToSet) / width;
float scaleHeight = ((float) heigthToSet) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
bmd = Utils.getRoundedCornerBitmap(resizedBitmap, color, 8, 0, EditReceiptActivity.this);
}
@Override
protected String doInBackground(Void... arg0) {
int Measuredwidth;
int Measuredheight;
Point size = new Point();
WindowManager w = getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
} else {
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
setImageView(Measuredheight - Utils.dpToPx(120, EditReceiptActivity.this), Measuredwidth - Utils.dpToPx(60, EditReceiptActivity.this),
Color.TRANSPARENT);
return null;
}
@Override
protected void onPostExecute(String result) {
loaderImageView.hideProgress();
image.setImageBitmap(bmd);
image.setBackgroundColor(Color.TRANSPARENT);
// center the Image
image.setScaleType(ScaleType.FIT_CENTER);
super.onPostExecute(result);
}
}