2013-01-17 58 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

相关问题