From the doc,
For Resources.getString()
:
Return the string value associated with a particular resource ID. It
will be stripped of any styled text information.
For Resources.getText()
:
Return the string value associated with a particular resource ID. The
returned object will be a String if this is a plain string; it will be
some other type of CharSequence if it is styled.
[Note that Context.getText()
and Context.getString()
internally calls the methods from Resources
.]
The doc says that getText()
retains the styling while the getString()
not. But you can use either one to get the string resource with HTML tags from strings.xml
, but the way is different.
Using Resources.getText():
strings.xml
:
<string name="styled_text">Hello, <b>World</b>!</string>
You can just call getText()
(note that it returns a CharSequence
not a String
, so it has the styling properties) and set the text to TextView
. No need for Html.fromHtml()
.
mTextView.setText(getText(R.string.styled_text));
But the doc says only a limited HTML tags, such as <b>, <i>, <u>
are supported by this method. The source code seems to suggest it supports more than that: <b>, <i>, <u>, <big>, <small>, <sup>, <sub>, <strike>, <li>, <marquee>, <a>, <font> and <annotation>
Using Resources.getString():
strings.xml
:
<string name="styled_text"><![CDATA[Hello, <b>World</b>!]></string>
You have to surround your string in a CDATA
block and calling getString
will return the string with HTML tags. Here you have to use Html.fromHtml()
.
mTextView.setText(Html.fromHtml( getString(R.string.styled_text)));
Html.fromHtml()
is deprecated in favor of a new method with flags
parameter. So use it like this:
HtmlCompat.fromHtml(getString(R.string.styled_text))
Implementation of the util method HtmlCompat.fromHtml
:
public class HtmlCompat {
public static CharSequence fromHtml(String source) {
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
//noinspection deprecation
return Html.fromHtml(source);
} else {
return Html.fromHtml(source, Html.FROM_HTML_MODE_COMPACT);
}
}
}