[英]Updating an ImageView with an image from a URL
在我的Android应用程序中,我想要使用从URL指定的图像更新ImageView。 此URL已作为AsyncTask的一部分通过API提取。
我定义了ImageView如下:
<ImageView
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:layout_height="wrap_content"
android:id="@+id/product_image"
android:src="@drawable/no_product_image"
android:layout_marginRight="6dip"
android:layout_width="wrap_content"
/>
这样,在加载数据时,ProgressDialog后面会出现一个空白图像。
在获取产品详细信息之后,作为AsyncTask的doInBackground的一部分,我致电:
private void createProductScreen(Product product){
Log.i(TAG, "Updating product screen");
//Set the product image
ImageView imgView =(ImageView)findViewById(R.id.product_image);
Drawable drawable = loadImageFromWeb(product.getImageUrl());
imgView.setImageDrawable(drawable);
Log.i(TAG, "Set image");
}
该图像是从Web加载的,如下所示:
private Drawable loadImageFromWeb(String url){
Log.i(TAG, "Fetching image");
try{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src");
Log.i(TAG, "Created image from stream");
return d;
}catch (Exception e) {
//TODO handle error
Log.i(TAG, "Error fetching image");
System.out.println("Exc="+e);
return null;
}
}
当它运行时,我在日志中看到“从流创建的图像” ,但是没有看到“设置图像”,并且从不调用AsyncTask的onPostExecute。
是否有人对此问题有任何想法,或者有将图像从空白图像更新为产品图像的更好方法?
因为您尝试在单独的线程中设置ImageView,所以应该得到一个Exception。 imgView.setImageDrawable(drawable);
必须在同一个UI线程中调用。 由于您使用的是AsyncTask类,因此设置imageview对象的正确位置在onPostExecute方法中。 更改逻辑,使doInBackground将Drawable对象返回到onPostExecute方法,然后使用它调用imgView.setImageDrawable(drawable);
将Imageview设置为可绘制图像
Drawable drawable = loadImageFromWeb(product.getImageUrl());
这是问题。
Drawable drawable = loadImageFromWeb(XXXXUrl);
Imageview.setImageDrawable(drawable);
给可绘制的正确的URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.