Android: html in strings.xml
To embed HTML in strings.xml, use CDATA:
To display the HTML in a TextView, invoke Html.fromHtml:
Always make sure to use android.text.Html.fromHtml()
for accurate HTML rendering.
Making hyperlinks interactive
A lot of texts are more useful when they come with clickable links. To make these links interactive within your TextView, first, enable this feature:
And then, specify this in your XML layout:
How to escape HTML symbols
When you are working with strings.xml
, remember to escape HTML entities to avoid errors:
By escaping these signs, you ensure that they are interpreted correctly.
Keeping text preformatted
Maintain whitespace and line breaks within your strings.xml by using the <pre>
HTML tag:
Then feed it to TextView:
Switching to WebView for complex HTML
Complex or advanced HTML display might just be out of TextView's paygrade. In such a case, switch to a WebView:
And load your fancy HTML into it:
Text styling with <span>
tag
Specific parts of your text may require their own unique styles. Do it using the <span>
tag:
Uniform text appearance
Text appearance can be adjusted to give a consistent look and feel throughout the application. Use the android:textAppearance
attribute for that uniformity:
This way, your app maintains a consistent font face, size and color.
Tackling long content
When your HTML content is long, wrap the TextView with a ScrollView for better user experience:
Including images
Including images is possible. Use an ImageView
and blend in image-loading libraries like Glide or Picasso to simplify things.
Store and access HTML strings
To keep your code clean and manageable, keep your formatted strings in strings.xml
and pull them when required with getString()
.
Was this article helpful?