2013-01-17 57 views
6

在項目中,我有一個文件:Android webview loadDataWithBaseURL如何從資產中加載圖片?

"MyProject/assets/folder1/image1.jpg" 
"MyProject/assets/folder1/index.html". 

在web視圖我需要打開index.html(含圖片)。

我嘗試這種代碼:

但圖像不加載。

如果我將圖像放到「assets」目錄(MyProject/assets/)並且使baseUrl = "file:///android_asset"圖像加載正確;

如何從根資產目錄中加載圖像,而不是從assets/folder1加載圖像?

+0

前段時間我看到一篇關於這個主題的長篇文章。如果你仍然需要一些幫助,請查看它。 http://devblog.morethanheroic.com/2017/01/03/how-to-create-an-app-from-a-static-website/ –

回答

-6

你給互聯網許可?

<uses-permission android:name="android.permission.INTERNET" /> 
+0

認真?如果他說把他們放在一個文件夾中表現得很好,意味着他必須得到許可。 – Darpan

8

嘗試這樣

WebView webview = (WebView)this.findViewById(R.id.webview); 


String html = "<html><head><title>TITLE!!!</title></head>"; 
html += "<body><h1>Image?</h1><img src=\"icon.png\" /></body></html>"; 


webview.loadDataWithBaseURL("file:///android_res/drawable/", html, "text/html", "UTF-8", null); 

欲瞭解更多信息,嘗試這種link

完美LoadDataWithBaseurl

+0

聽說此函數的'baseURL'將忽略在第一個/之後發生的任何事情。 – Darpan

1

嘗試喜歡這個

try { 
      String filePath = null; 
      filePath = "Your File path"; 
      Bitmap bitmap = null; 

      bitmap = BitmapFactory.decodeFile(filePath); 
      Log.v("Image data-->", "" + bitmap); 
      imageWidth = bitmap.getWidth(); 
      imageHeight = bitmap.getHeight(); 
      Log.e("Width", "" + imageWidth); 
      filePath = "file://" + filePath; 
      String html = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html\";charset=utf-8\"/><title></title></head><body style=\"width:" 
        + imageWidth 
        + "px; height:" 
        + imageHeight 
        + "px; background:url(" 
        + filePath 
        + ") no-repeat; position:relative;\">" 
        + getDivTag(mapList) 
        + "</body></html>"; 

      Log.v("MIS", "" + html); 
      webview.getSettings().setSupportZoom(true); 
      webview.loadDataWithBaseURL(null, html, "text/html", "utf-8", null); 

      System.out.println(html); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
4

我認爲你必須設置的基礎資產和子文件夾添加到您的圖片src的是這樣的:

webView.loadDataWithBaseURL("file:///android_asset/", readAssetFileAsString("folder1/index.html"), "text/html", "UTF-8", null);

HTML: <img src="folder1/image1.jpg">

這爲我工作在Android 5.1

private String readAssetFileAsString(String sourceHtmlLocation) 
{ 
    InputStream is; 
    try 
    { 
     is = getContext().getAssets().open(sourceHtmlLocation); 
     int size = is.available(); 

     byte[] buffer = new byte[size]; 
     is.read(buffer); 
     is.close(); 

     return new String(buffer, "UTF-8"); 
    } 
    catch(IOException e) 
    { 
     e.printStackTrace(); 
    } 

    return ""; 
} 
+0

該方法'readAssetFileAsString'在哪裏? – zygimantus

+1

添加了方法代碼,此代碼之前是從另一個SO帖子中提取的,但不幸的是我沒有鏈接來表明他們的功勞 – behelit

相關問題