0

ImageView(来自 URL 的图像)无法在 Fragment 中显示(意味着空白屏幕)。

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

在活动页面显示是正确的,但是当我更改为 Fragment 时,它根本无法显示。请让我知道有什么问题。

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

1 回答 1

-2

修复它是因为我的变量传递是错误的。

于 2012-10-09T11:14:47.320 回答