Search code examples
androidxmlstring-formatting

Bold characters in string.xml are not shown on screen


In my string.xml file, I have something like this:

<string name="example_string"><b>This</b> is a <b>%1$s</b></string>

And then I placed it into a TextView:

textView.setText(getString(R.string.example_string, "good question"));

The "good question" argument that I passed to the getString() method is not shown in bold. Even the word "This" is not shown in bold! What's the reason for this and how to solve it?

=========================================================================

I know how to use Html.fromHtml(), but this method does not support inserting a string to the place holder that I have defined in the string resource. If you are trying to tell me that Html.fromHtml() exists, please DO NOT REPLY...


Solution

  • So after a day of search, I found the desired answer on Android Developers website! The Link to the page is here: https://developer.android.com/guide/topics/resources/string-resource.html

    Sometimes you may want to create a styled text resource that is also used as a format string. Normally, this won't work because the String.format(String, Object...) method will strip all the style information from the string. The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String), after the formatting takes place.

    Basicaly, the change that I would make based on my original question is to replace the bracket "<" with the HTML tag for that, which is "&lt" + ";" (Type them together in your xml file! I had to separate them because StackOverflow will diplay the tag as the bracket itself.) For more detailed explanation, please see the Styling with HTML markup section from the website that I posted above.