【问题标题】:Rendering String as HTML in android webview在android webview中将字符串呈现为HTML
【发布时间】:2019-05-29 20:21:36
【问题描述】:

我有一个需要在 Webview 中呈现的字符串,但遇到了问题。 字符串如下。

History
            Riots and political conflicts of the 1960s


--------Line Feed1----------------


              The LAPD Metropolitan Division's "D" Platoon is one of the world's most prominent SWAT units and was the second SWAT team established in the United States, after that of the Philadelphia Police Department in 1964.[2]
According to the Historical Dictionary of Law Enforcement, the term "SWAT" was used as an acronym for the "Special Weapons and Tactics" established as a 100-man specialized unit in 1964 by the Philadelphia Police Department in response to an alarming increase in bank robberies. 

--------Line Feed2----------------


                  The purpose of this unit was to react quickly and decisively to bank robberies while they were in progress, by utilizing a large number of specially trained officers who had at their disposal a great amount of firepower. The tactic worked and was later soon to resolve other types of incidents involving heavily armed criminals.[2][3] Los Angeles Police Department (LAPD) Inspector Daryl Gates has said that he first envisioned "SWAT" as an acronym for "Special Weapons Attack Team" in 1967, but later accepted "Special Weapons and Tactics" on the advice of his deputy chief, Edward M. Davis.[4]


<p>&#160;</p>
<p><span><img src="https://upload.wikimedia.org/wikipedia/commons/1/19/Flag_of_Andorra.svg" border="0" alt="" /></span></p>
<p>&#160;</p>

方法一: 当我使用上面的字符串传递给webview时(str是上面提到的字符串)

webview.loadDataWithBaseURL(null,str,"text/html","utf-8",null)

结果如下图A所示。这里的问题是换行符(\n)和空格被webview删除了。

方法二: 当我使用

将上面的字符串传递给 webview
webview.loadDataWithBaseURL(null,Html.toHtml(SpannableString(str)),"text/html","utf-8",null)

结果如下图B所示。这里的问题是换行符 (\n) 和空格显示正确,但 HTML 也显示为纯文本。

方法 3: 当我使用

将上面的字符串传递给 webview
 webview.loadDataWithBaseURL(null,str.replace("\n",<br/>"),"text/html","utf-8",null)

结果如下图C所示。这里的问题是换行符 (\n) 和 HTML 正确呈现,但段落开头的空格没有显示。

我的要求是实现如下图D所示

达到预期结果的最佳解决方案是什么。 我创建了一个示例应用程序here 供参考。

【问题讨论】:

    标签: android android-webview


    【解决方案1】:

    你掌握了 HTML 字符串吗?如果是,您应该将文本内容移动到 &lt;p&gt; 标记中,并在左侧添加填充而不是空格。

    喜欢这里解释:https://stackoverflow.com/a/1571662/6809926

    【讨论】:

    • 我无法编辑字符串...它可以是任何东西,由最终用户设置。
    • 好的,您可以使用正则表达式将空格替换为 &amp;nbsp; (source) 以确保空格将被 Web 视图解释。
    猜你喜欢
    • 2015-02-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 2022-12-01
    • 2016-05-21
    相关资源
    最近更新 更多