Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 451
Thomas W Chen Avatar asked Jul 25 '16 14:07

Thomas W Chen


People also ask

How do I bold text in a string?

text. style. StyleSpan(Typeface. BOLD), start, end, Spannable.

How do you bold a string in Javascript?

The bold() method creates a <b> HTML element that causes a string to be displayed as bold.


Video Answer


2 Answers

i've had success using getText instead of getString. It seems to maintain styling.

from the docs:

You can use either getString(int) or getText(int) to retrieve a string. getText(int) retains any rich text styling applied to the string.

like image 68
j2emanue Avatar answered Oct 06 '22 16:10

j2emanue


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.

like image 20
Thomas W Chen Avatar answered Oct 06 '22 14:10

Thomas W Chen