加载图像并在完成加载时设置它

Load image and set it when it's finish loading

我有一个 AsyncTask 获取一个 URL 作为参数,并且 returns 一个来自 URL 的图像的 Bitmap 当它完成时.当我启动 activity 时,我想在背景中显示 "loading..."、运行 和 ImageFetcher 的文本(而不是图像),当它完成时,设置图像到 ImageView

问题是,如果我 运行:

ivPoster.setImageBitmap(imgFetcher.execute(m.getPosterUrl()).get());

在加载图像之前,它不会加载整个 activity。它跳帧。

所以我在任务上设置了一个完成侦听器,即 returns 位图,并尝试在检索到位图后设置图像:

imgFetcher.setOnFinishListener(new OnTaskFinished() {

    @Override
    public void onFinish(Bitmap bm) {
        // hide the loading image text
        tvLoading.setVisibility(View.INVISIBLE);
        // place the image
        ivPoster.setImageBitmap(bm);
    }
});

imgFetcher.execute(m.getPosterUrl());

但它仍然跳帧 'does too much work on the main thread'。
如何防止跳帧?

可以考虑Picasso lib:http://square.github.io/picasso/

通用图像加载器:https://github.com/nostra13/Android-Universal-Image-Loader

您可以改用 AsyncTask 中的 UI 线程。如果您 运行 该线程中的代码加载图像,则程序的其余部分将不必等待。

使用此 documentation 获得更多见解。您可以使用 onPostExecute() 方法或 onProgressUpdate() 方法,而不是在后台线程中引起等待。

主线程与UI线程相同。您应该使用它来更改 UI。这样您的应用程序就不会在执行后台代码之前等待图形加载,而是同时执行它们。为了使用 AsyncTask 中的 ImageView,如果 AsyncTask 是子类并在执行前实例化,则可以将 ImageView 设为全局。否则,将其作为参数传递给 AsyncTask。

private class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
    ImageView mImageView;
    String mUrl;

    public ImageDownloaderTask(ImageView imageview, String url) {
        this.mImageView = imageview;
        this.mUrl = url;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        //Download here

    }

    @Override
    // Once the image is downloaded, associate it to the imageView
    protected void onPostExecute(Bitmap bitmap) {
        mImageView.setImageBitmap(bitmap);
    }
}

希望代码片段对您有所帮助