android - 如何在使用 AsyncTask 下载图像时显示默认图像?

标签 android listview android-asynctask

我正在使用AsyncTask从远程服务器下载图像并将其显示在ListView中。我正在使用 this blog 完成它,一切都工作正常。

此博客中的唯一问题是在下载图像时显示 ColorDrawable。但我想在下载图像时显示默认图像。就像下面的附图一样:

image list

在这里您可以看到:

  1. Taylor Loother 和 Oye Oye 的图片已下载。
  2. 服务器上没有 Gopala Govinda 的图像,所以我没有 从服务器下载他的图像并显示默认图像。
  3. 对于 hell 男爵,图像仍在下载中,因此颜色 背景(细黑线)出现在他的名字旁边。 我 不想显示这条黑线。我想显示默认值 图像 就像在 Gopala Govinda 面前一样,直到图像不再 从 hell 男爵的服务器加载。

    有人知道如何做到这一点吗?

最佳答案

我认为您想要做的是让 DownloadedDrawable 类扩展 BitmapDrawable 而不是 Drawable,然后选择适当的 super 之一构造函数来指定默认图像位图:

/**
 * A fake Drawable that will be attached to the imageView while the download is in progress.
 *
 * Contains a reference to the actual download task, so that a download task can be stopped
 * if a new binding is required, and makes sure that only the last started download process can
 * bind its result, independently of the download finish order.</p>
 */
private static class DownloadedDrawable extends BitmapDrawable {
    private final WeakReference<BitmapDownloaderTask> 
       bitmapDownloaderTaskReference;

    private DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask,
       Resources resources, Bitmap bitmap) {
        super(resources, bitmap); // you'll have to provide these
        bitmapDownloaderTaskReference =
            new WeakReference<BitmapDownloaderTask>(bitmapDownloaderTask);
    }

    public BitmapDownloaderTask getBitmapDownloaderTask() {
        return bitmapDownloaderTaskReference.get();
    }
}

关于android - 如何在使用 AsyncTask 下载图像时显示默认图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12386411/

相关文章:

java - Android:TextView,unicode 字符未正确显示

android - 如何通过单击Webview中的youtube搜索页面链接获取视频ID

android - 使用 9-patch png 创建薄分隔线

c# - 如何在 Xamarin Forms 中制作卡片样式的 ListView

android - 获取android ListView中选中项的数量

长按项目的 Android 4.0+ 列表选择器 - 需要持久 - 不工作

java - 在 doInBackground 中创建一个处理程序

android - 是否可以在新线程中启动服务?

android - 如何将我的数据库的 AsyncTask 与 android 中的谷歌地图结合起来?

android - AsyncTask 和 Activity 怎么做