【问题标题】:Updating an ImageView with an image from a URL使用来自 URL 的图像更新 ImageView
【发布时间】:2010-11-20 23:17:56
【问题描述】:

在我的 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");
}

图片从网络加载如下:

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;
        }
    }

当它运行时,我在日志中看到 "Created image from stream",但没有看到 "Set image" 并且永远不会调用 AsyncTask 的 onPostExecute .

是否有人对此问题有任何想法或将图像从空白图像更新为产品图像的更好方法?

【问题讨论】:

标签: java android


【解决方案1】:

你应该得到一个异常,因为你试图在一个单独的线程中设置 ImageView。 imgView.setImageDrawable(drawable); 必须在同一个 UI 线程中调用。 由于您使用的是 AsyncTask 类,因此设置 imageview 对象的正确位置是在 onPostExecute 方法内。 改变你的逻辑,使 doInBackground 将 Drawable 对象返回给 onPostExecute 方法,然后使用它调用imgView.setImageDrawable(drawable);

【讨论】:

    【解决方案2】:

    将 Imageview 设置为可绘制图像

    Drawable drawable = loadImageFromWeb(product.getImageUrl());
    

    这里有问题。

    Drawable drawable = loadImageFromWeb(XXXXUrl);
    Imageview.setImageDrawable(drawable);
    

    给drawable一个正确的URL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 2019-05-06
      相关资源
      最近更新 更多