我有从Internet端获取图像的代码在指定的ImageView中使用它。当我需要将图像分配到不同的ImageView时会出现问题。我发送两个参数到这个函数url和(int)i。使用它们我需要将图像分配给R.id.eventsImage0,R.id.eventsImage1或R.id.eventsImage2,具体取决于i(0,1或2)的值。我的代码是:
private class LoadImagefromUrl extends AsyncTask< Object, Void, Bitmap > {
ImageView ivPreview = (ImageView) pwindo.getContentView().findViewById(R.id.eventsImage0);
@Override
protected Bitmap doInBackground( Object... params ) {
// this.ivPreview =
String url = (String) params[0];
int i = (int) params[1];
System.out.println(url);
return loadBitmap( url );
}
@Override
protected void onPostExecute( Bitmap result ) {
super.onPostExecute( result );
ivPreview.setImageBitmap( result );
}
}
public Bitmap loadBitmap( String url ) {
URL newurl = null;
Bitmap bitmap = null;
try {
newurl = new URL( url );
bitmap = BitmapFactory.decodeStream( newurl.openConnection( ).getInputStream( ) );
} catch ( MalformedURLException e ) {
e.printStackTrace( );
} catch ( IOException e ) {
e.printStackTrace( );
}
return bitmap;
}
答案 0 :(得分:0)
尝试扩展您为任务提供的内容(目前只是一个字符串)。这是一个例子:
private class LoadImagefromUrlModel {
final int viewId;
final String url;
Bitmap bitmap;
/**
*
* @param url the url
* @param viewId the id of the imageview to display the loadded bitmap
*/
public LoadImagefromUrlModel(String url, int viewId) {
this.url = url;
this.viewId = viewId;
}
}
private class LoadImagefromUrl extends AsyncTask< LoadImagefromUrlModel, Void, LoadImagefromUrlModel > {
@Override
protected LoadImagefromUrlModel doInBackground( LoadImagefromUrlModel... params ) {
LoadImagefromUrlModel model = params[0];
// load the bitmap
model.bitmap = loadBitmap( model.url );
return model;
}
@Override
protected void onPostExecute( LoadImagefromUrlModel result ) {
super.onPostExecute(result);
// find the imageview
ImageView ivPreview = (ImageView) pwindo.getContentView().findViewById(result.viewId);
if (ivPreview != null) {
ivPreview.setImageBitmap(result.bitmap);
}
}
}
public Bitmap loadBitmap( String url ) {
URL newurl = null;
Bitmap bitmap = null;
try {
newurl = new URL( url );
bitmap = BitmapFactory.decodeStream( newurl.openConnection( ).getInputStream( ) );
} catch ( MalformedURLException e ) {
e.printStackTrace( );
} catch ( IOException e ) {
e.printStackTrace( );
}
return bitmap;
}
然后打电话,所以
new LoadImagefromUrl().execute(new LoadImagefromUrlModel("someurl", R.id.eventsImage));