简体   繁体   中英

How to prevent Html.fromHtml from trimming whitespace

In an Android Java project, I have a string like this one (although with varying amounts of whitespace on either side):

String foo = "  foo bar  "

The whitespace on the two sides of the string is important, as the actual string contains indented code with HTML syntax highlighting.

When I pass the string through Html.fromHtml , this start and end whitespace is removed, but I need to keep the whitespace there:

Html.fromHtml(foo).toString() // "foo bar" - I want "  foo bar  " 

How I can preserve the whitespace on the sides of the string through the Html.fromHtml call?

Try Using TextUtils.htmlEncode(str).

This method will escape all html string character.

https://developer.android.com/reference/android/text/TextUtils.html#htmlEncode(java.lang.String)

As Html.fromHtml() parses the string as html tags and content may be you want to use the encoded character for space which is  

try this in your code

String foo = "  foo bar  ";

Note: repeat   as many spaces as you need to show.

Edit: if you are getting your string from somewhere else, you can replace spaces with   before passing it

String foo = getMyFoo();
foo = foo.replaceAll(" "," ");

Yazan的建议是足够的,但是由于您说字符串是动态生成的,因此您始终可以以新生成的字符串s为例,并使用concat()方法。例如s.concat(“&nbsp”);

为了保留开始的空白,此Kotlin代码似乎可以工作,并且可能也不难适应于使用结束的空白:

fun replaceWithNonBreakingAtStart(str: String) = (1..(str.takeWhile { it == ' ' }.count())).map { " " }.joinToString("") + str.trimStart()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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