如何在webview中加载html字符串?

Nul*_*ion 47 android webview android-webview

我有一个包含这个的html字符串:

    <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
    <html>
      <head>
      <meta http-equiv="content-type" content="text/html; charset=windows-1250">
      <meta name="spanish press" content="spain, spanish newspaper, news,economy,politics,sports">  
      <title></title>
      </head>
      <body id="body">  
<!-- The following code will render a clickable image ad in the page -->
        <script src="http://www.myscript.com/a"></script>
      </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

我需要在android中将该网站显示为webview.

我试着用这一切:

webView.loadDataWithBaseURL(null, txt, "text/html", "UTF-8", null);
webView.loadDataWithBaseURL("x-data://base", txt, "text/html", "UTF-8", null);      
webView.loadDataWithBaseURL("notreal/", txt, "text/htm", "utf-8",null);
Run Code Online (Sandbox Code Playgroud)

我也尝试删除DOCTYPE标签:

txt=txt.replace("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">", "");

没有人有工作.我刚刚实现了将字符串显示到webview(html代码),但不是必须使用该html代码创建的网站.

怎么了?

小智 112

在WebView中加载数据.调用WebView的loadData()方法

wv.loadData(yourData, "text/html", "UTF-8");
Run Code Online (Sandbox Code Playgroud)

您可以查看此示例

http://developer.android.com/reference/android/webkit/WebView.html

[编辑1]

您应该添加 - \ - before - " - 例如 - > name = \"spanish press \"

下面的字符串为我工作

String webData =  "<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " +
"content=\"text/html; charset=utf-8\"> <html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1250\">"+
 "<meta name=\"spanish press\" content=\"spain, spanish newspaper, news,economy,politics,sports\"><title></title></head><body id=\"body\">"+
"<script src=\"http://www.myscript.com/a\"></script>?lkas?ldkas?dksa?dka?skd?k</body></html>";
Run Code Online (Sandbox Code Playgroud)

  • 不起作用,只是显示一个没有内容的空白视图。 (10认同)
  • 我们应该使用 `loadDataWithBaseURL` 代替,因为 `loadData` 不处理下一行 (`\n`) /sf/ask/351895911/ (3认同)

小智 11

你也可以试试这个

   final WebView webView = new WebView(this);
            webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
Run Code Online (Sandbox Code Playgroud)


小智 11

从资产 html 文件中读取

ViewGroup webGroup;
  String content = readContent("content/ganji.html");

        final WebView webView = new WebView(this);
        webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);

        webGroup.addView(webView);
Run Code Online (Sandbox Code Playgroud)