问与答 android-如何在webview中加载html字符串?

sherman · 2020-03-06 14:05:07 · 热度: 67

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

我需要将该网站显示为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);

我也尝试删除DOCTYPE标签:

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

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

怎么了?

猜你喜欢:
共收到 4 条回复
kermit #1 · 2020-03-06 14:05:08

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

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

您可以检查这个例子

[HTTP://developer.Android.com/reference/Android/WebKit/Web view.HTML]

[编辑1]

您应该在-之前加上-\--例如-> 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>";
selwyn #2 · 2020-03-06 14:05:09

从资产读取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);
clark #3 · 2020-03-06 14:05:11

您也可以尝试一下

   final WebView webView = new WebView(this);
            webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
wyatt #4 · 2020-03-06 14:05:12

我有相同的要求,并且已经按照以下方式进行了操作。您也可以尝试一下。

使用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>Director : </strong>"+movDirector+"</p><p><strong>Producer : </strong>"+movProducer+"</p><p><strong>Character : </strong>"+movActedAs+"</p><p><strong>Summary : </strong>"+movAnecdotes+"</p><p><strong>Synopsis : </strong>"+movSynopsis+"</p>\n","text/html", "UTF-8");

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

简而言之,我为自己的网址保留自定义样式。

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册