简体   繁体   English

如何以正确的格式在Android WebView中显示html文本?

[英]How to show html texts in Android WebView in proper format?

I have a string which contains html texts and images parsed from a json file.I need to show it in webview .The string consists of 3-4 paragraph but while displaying in webview it shows like one paragraph ie the android webview skips the breakline tags.But my requirement is to show as it is in the website with proper alignment.Please help me. 我有一个字符串,其中包含从json文件中解析的html文本和图像。我需要在webview显示它。该字符串包含3-4段,但是在webview显示时它显示为一个段落,即android webview跳过了breakline标签。但我的要求是在网站上以正确的对齐方式显示。请帮助我。

my Json file link is this 我的Json文件链接是这个

and my webview code is 而我的webview代码是

//newsContent contains the json string after parsing.

  String all="<html><body>"+newsContent+"</body></html>";

                 tv.getSettings().setJavaScriptEnabled(true); 
                 tv.getSettings().setPluginsEnabled(true);
                 tv.getSettings().setSupportZoom(false);
                 tv.getSettings().setAllowFileAccess(true);
                 WebSettings webSettings = tv.getSettings();
                 tv.getSettings().setAllowFileAccess(true);
                 webSettings.setTextSize(WebSettings.TextSize.NORMAL);

                 tv.loadDataWithBaseURL(null,all, "text/html", "UTF-8", null);

The problem lies with "\\r\\n" in your json data. 问题在于您的json数据中存在“ \\ r \\ n”。 Look like \\r\\n work only if they are wrapped in tag. 看起来\\ r \\ n仅在将它们包装在标签中时才起作用。 Easy solution would be replace \\r\\n with 简单的解决方案是将\\ r \\ n替换为
tag. 标签。

String all="<html><body>"+newsContent.replace("\\r\\n", "<br/>")+"</body></html>";

String text = "<html><body style=\"text-align:justify\"> %s </body></Html>";
String data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ac quam risus, at tempus justo. Sed dictum rutrum massa eu volutpat. Quisque vitae hendrerit sem.";
WebView webView = (WebView) findViewById(R.id.WebView);
webView.loadData(String.format(text, data), "text/html", "utf-8");

Below works. 下面的作品。 There should be double slash \\r\\n 应该有双斜杠\\ r \\ n

String all=""+newsContent.replace("\\r\\n", "
")+"";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM