Friday, June 29, 2018

Formatting for <pre> tag with white space and line breaks Android

Leave a Comment

I was able to set my own Tag Hanlder using this example: Android: How to use the Html.TagHandler?

Everything worked until I hit this example:

<pre class="prettyprint linenums">    Some Code()\n   more code </pre> 

This is transformed into

HtmlCompat.fromHtml(context, html, HtmlCompat.FROM_HTML_MODE_COMPACT, null, CustomTagHandler()) 

The fromHtml method can't seem to handle the white space and \n it will ignore both and skip setting any Span on this tag.

My only option is to replace the white space and \n BEFORE calling fromHtml with the following:

html.replace("  ", "&nbsp;&nbsp;")     .replace("\n", "<br />") 

This is to me is a bad solution. First, not all of the Htmls will have a pre tag, and it skips single spaces, because it will replace to this <pre&nbsp;class... which would fail all together.

I tried editing the handleTag method in the CustomTagHandler which has the output

  Some Code()\n   more code  

but replace the String there doesn't work.

Any suggestions on setting a Span for tags that have white space and line breaks?

The goal is to preserve the line breaks and white space and add a Monospace to the text.

1 Answers

Answers 1

 myTextView.setText (Html.fromHtml(text.toString(), null, new MyHtmlTagHandler()));  
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment