Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: format string and add bold style

I have a string in my resource:

<string name="region"><b>Region:</b> %1$s</string>

I am trying to set this text to a textview:

tvRegion.setText(Html.fromHtml(R.string.region, "France"));

The problem is that the string "region" is not bold !

like image 456
Zbarcea Christian Avatar asked Aug 08 '14 10:08

Zbarcea Christian


3 Answers

From the official documentation:

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.

You need to HTML-escape the opening bracket of html tags, when inserting it in any xml resource file.

<string name="region">&lt;b>Region:&lt;/b> %1$s</string>
like image 178
BackSlash Avatar answered Sep 26 '22 13:09

BackSlash


Here's how you can do that in xml:

<string name="region"><![CDATA[<b>Region:</b> %1$s]]></string>

And the java code:

String str = getString(R.string.action_about_msg, "France");
tvRegion.setText(Html.fromHtml(str));
like image 43
Simas Avatar answered Sep 22 '22 13:09

Simas


You can use HTML text directly in Html.fromHtml() method.. try this way..

tvRegion.setText(Html.fromHtml("<b>" + yourtext+ "</b>" + "Other text.."));

with this you can style your string with HTML tags.. as you want..

like image 36
Pragnesh Ghoda シ Avatar answered Sep 24 '22 13:09

Pragnesh Ghoda シ