【问题标题】:displaying preloaded bitmap in webview在 webview 中显示预加载的位图
【发布时间】:2012-05-01 18:11:55
【问题描述】:

我有一个自定义 ListView 可以延迟加载远程图像。当您单击一个列表项时,它会启动一个新 Activity 并在 webview 中显示图像。 问题是,webview 总是加载图像,即使图像是由 listview 适配器预加载的。我希望 WebView 在未预加载的情况下加载图像!

这是我在列表视图中预加载图像的方式:

public void DisplayImage(String url, ImageView imageView)
{
    imageViews.put(imageView, url);
    Bitmap bitmap=memoryCache.get(url);
    if(bitmap!=null)
        imageView.setImageBitmap(bitmap);
    else
    {
        queuePhoto(url, imageView);
        imageView.setImageResource(stub_id);
    }
}

延迟加载的图像存储在 FileCache 中:

public FileCache(Context context){
    //Find the dir to save cached images
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
    else
        cacheDir=context.getCacheDir();
    if(!cacheDir.exists())
        cacheDir.mkdirs();
}

public File getFile(String url){
    //I identify images by hashcode. Not a perfect solution, good for the demo.
    String filename=String.valueOf(url.hashCode());
    //Another possible solution (thanks to grantland)
    //String filename = URLEncoder.encode(url);
    File f = new File(cacheDir, filename);
    return f;

}

【问题讨论】:

    标签: android webview bitmap


    【解决方案1】:

    处理这个问题的正确方法是安装一个HttpResponseCache 与您用于下载图像的客户端/连接。尽管直到 API 级别 13 才提供平台实现,但有一个适用于 Android 1.5 及更高版本的backported version。不过这种缓存机制只适用于Http(s)URLConnection;如果您使用HttpClient,您将需要Apache 的HttpClient Caching Module

    如果您想要快速解决方案,您还可以查看WebViewClientshouldInterceptRequest(...) 方法。通过覆盖该方法,如果我没记错的话,您可以拦截在即将获取资源(包括图像)时触发的请求。您可以执行一个检查来执行本地查找以查看图像是否已下载,如果是,则将其返回包装在 WebResourceResponse 中。如果文件在本地不可用,只需不做任何事情,让客户端处理下载。这样做的缺点是 webclient 下载的任何内容都不会被惰性图像加载器使用。

    【讨论】:

    • 谢谢,我正在尝试 shouldInterceptRequest 方法,但是这个方法永远不会被调用!有什么建议吗?
    • 臭虫,我忘了说这是一种 Honeycomb+ 方法……这意味着它不会在旧设备上被调用。您可能必须遵循我的第一个建议。或者,您可以在将图像 url 传递给 WebView 之前进行检查(这就是您在其中显示的所有内容,对吗?)以查看它是否存在于本地。如果是,则传递本地 URL,否则传递远程 URL。
    猜你喜欢
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    相关资源
    最近更新 更多