2012-05-01 15 views
2

我有一個自定義的ListView,可以實現延遲加載的遠程圖像。當你點擊一個listitem時,它會啓動一個新的Activity並在webview中顯示圖像。 問題是,即使圖像是由列表視圖適配器預加載的,web視圖始終會加載圖像。如果沒有預加載,我想讓WebView加載圖像只有在webview中顯示預加載的位圖

這裏是我預載的圖片在ListView:

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; 

} 

回答

1

正確的方式來處理,這是安裝一個HttpResponseCache與您用於下載圖像的客戶端/連接。儘管在API級別13之前沒有提供平臺實現,但有一個適用於Android 1.5或更高版本的backported version。這個緩存機制雖然只適用於Http(s)URLConnection;如果您使用HttpClient,則需要Apache的HttpClient Caching Module

如果您想要快速解決問題,可以參考WebViewClientshouldInterceptRequest(...)方法。通過重寫該方法,如果我沒有弄錯,您可以攔截在獲取資源時觸發的請求,包括圖像。您可以執行一次檢查,執行本地查找以查看圖像是否已經下載,如果是,請將其以WebResourceResponse的形式返回。如果該文件不在本地可用,則不要執行任何操作並讓客戶端處理下載。這樣做的缺點是,由webclient下載的任何內容都不能用於懶惰的圖像加載器。

+0

謝謝,我正在嘗試shouldInterceptRequest方法,但此metod永遠不會被調用!任何建議? –

+0

Bugger,我忘了提及它是一個Honeycomb +方法......這意味着它不會在較舊的設備上調用。你可能不得不遵循我的第一個建議。或者,您可以在將圖像url傳遞給「WebView」之前進行檢查(這就是您在此顯示的所有內容,對吧?),以查看它是否存在於本地。如果是這樣,請傳遞本地URL,否則傳遞遠程URL。 –