如何在UI中设置图像,从另一个运行asynctask的类中获取图像(位图)? 我认为我可以使用AsyncTask.get()在线程完成时在UI中执行某些操作,但我认为这不是最好的方法,这里是Activity的代码和要下载图像的类:
public class Recipe extends Activity {
private ImageView image;
private static final String baseURL = "http://x/images/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipe_activity);
Intent i = getIntent();
GetRecipe getR = new GetRecipe(i.getStringExtra("id"));
getR.getId();
TextView title = (TextView) findViewById(R.id.tvRecipeTitle);
title.setText(getR.getName());
TextView description = (TextView) findViewById(R.id.tvRecipeDescription);
description.setText(getR.getDescription());
String imageURL = getR.getImage();
Log.d("Recipe", "setting image");
image = (ImageView) findViewById(R.id.ivRecipe);
Log.d("Recipe", "Image url: " + imageURL);
// Download image
GetRecipeImage GRI = new GetRecipeImage(baseURL + imageURL, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.recipe, menu);
return true;
}
// This method should be called when image is full downloaded
public void setImageView(Bitmap bp) {
image.setImageBitmap(bp);
}
}
public class GetRecipeImage {
private Context context;
private String url;
// private Bitmap downloadedImage = null;
// private AsyncTask<Void, Void, Void> GIAsyncTask;
public GetRecipeImage(String url, Context context) {
this.context = context;
this.url = url;
new DownloadImageTask().execute();
}
public static Bitmap getBitmapFromAsset(Context con) {
AssetManager assetManager = con.getAssets();
InputStream istr;
Bitmap bitmap = null;
try {
istr = assetManager.open("imagenotfound.png");
bitmap = BitmapFactory.decodeStream(istr);
} catch (IOException e) {
return null;
}
return bitmap;
}
private Bitmap imageNotFound() {
return getBitmapFromAsset(context);
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
Log.d("GRI", "getting image");
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
if (mIcon11 == null) {
return imageNotFound();
} else {
return mIcon11;
}
}
protected void onPostExecute(Bitmap result) {
// context.getClass().getSimpleName().setImageView();
}
}
}
感谢您的关注!
答案 0 :(得分:0)
为什么在AsyncTask已经是内部类的情况下获取上下文?
只需拨打Recipe.this
..
protected void onPostExecute(Bitmap result) {
Recipe.this.setImageView(result);
}