簡體   English   中英

使用URL中的圖像更新ImageView

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM