Android如何在片段中显示URL中的图像

时间:2012-10-09 05:34:04

标签: android

ImageView(来自网址的图片)无法在片段中显示(表示空白屏幕)。

ImageView newsimage = (ImageView) findViewById(R.id.newsimg);
ImageLoad downloader = new ImageLoad(newsimage);
downloader.execute("http://www.mysite.com/pp.jpg");

在“活动”页面中显示是正确的,但是当我更改为Fragement时,它根本无法显示。请让我知道有什么不对。

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

public class ImageLoad extends AsyncTask<String, Void, Bitmap> {

    private String url;
    private final WeakReference<ImageView> imageViewReference;

    public ImageLoad(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    protected Bitmap doInBackground(String... params) {
        url = params[0];
        try {
            return BitmapFactory.decodeStream(new URL(url).openConnection()
                    .getInputStream());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected void onPostExecute(Bitmap result) {
        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(result);
            }
        }
    }

    protected void onPreExecute() {
        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageResource(R.drawable.no_image);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:-2)

修正了因为我的变量传递错误。