如何在Webview中加载HTML字符串?

76

我有一个包含以下内容的 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>

我需要在安卓应用中将网站显示在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);

我也试过移除 DOCTYPE 标签:

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

但都没有生效。我只能在 WebView 中显示字符串(HTML 代码),而不能显示由该 HTML 代码创建的网站。

出了什么问题?


你尝试过使用 loadData 吗? - njzk2
你可以将这个HTML字符串放到文件res/values/strings.xml中,并创建一个项目,例如<string name="website">your html here</string>,然后通过Html.fromHtml(getString(R.string.website))来加载它。如果你有时间,请检查一下它是否有效,因为我也想知道它是否可行 ;) - deadfish
你到底为什么需要基础URL呢? - njzk2
1
@Lumma:Html.fromHtml 不适用于 webView。它返回一个 Spanned,用于 TextViews。 - njzk2
5个回答

161

要在WebView中加载您的数据。调用WebView的loadData()方法。

wv.loadData(yourData, "text/html", "UTF-8");

您可以查看这个例子

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>";

12
无法工作,仅显示一个空白视图,没有任何内容。 - NullPointerException
1
为了正确使用UTF-8,您应该使用webView.loadData(data,"text/html; charset=UTF-8;", null);,参见https://dev59.com/YG865IYBdhLWcg3wKLJP#9312031。 - Boris Treukhov
4
因为loadData不能处理换行符\n,所以我们应该使用loadDataWithBaseURL - Linh
数据 =“<iframe ... </ iframe>”无法工作,获取空视图。 - hmac
在使用loadData之前,请查看此链接:https://goyalnitesh.medium.com/how-to-load-an-html-string-in-a-webview-in-googles-recommended-way-2cd6e8788e3 - undefined

18

你也可以尝试这个。

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

12

从资产中读取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);

1

我有同样的需求,我是用以下方式完成的。你也可以试试这个方法。

使用loadData方法

web.loadData("<p style='text-align:center'><img class='aligncenter size-full wp-image-1607' title='' src="+movImage+" alt='' width='240px' height='180px' /></p><p><center><U><H2>"+movName+"("+movYear+")</H2></U></center></p><p><strong>导演:</strong>"+movDirector+"</p><p><strong>制片人:</strong>"+movProducer+"</p><p><strong>角色:</strong>"+movActedAs+"</p><p><strong>简介:</strong>"+movAnecdotes+"</p><p><strong>剧情简介:</strong>"+movSynopsis+"</p>\n","text/html", "UTF-8");

movDirector movProducer 都是我的字符串变量。

简而言之,我保留了自定义样式的 URL。


0
如果你在寻找JetpackCompose相关的内容,这可以帮到你:
@Composable 
fun HtmlTextVisualizerComponent(textFromData: String) {
val mimeType = "text/html"
val encoding = "UTF-8"

LazyColumn(
    modifier = Modifier
        .padding(
            start = 24.dp,
            end = 24.dp,
            top = 16.dp,
            bottom = 24.dp,
        ),
) {
    items(1) {
        val state = rememberWebViewState(
            url = "data:$mimeType;$encoding,$textFromData",
        )
        val navigator = rememberWebViewNavigator()
        WebView(
            state = state,
            modifier = Modifier.fillMaxSize(),
            navigator = navigator,
            onCreated = {
                it.settings.javaScriptEnabled = true
            },
        )
    }
  }
}

确保不要忘记在你的Gradle中添加依赖:

 implementation "com.google.accompanist:accompanist-webview:0.30.1"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接