Html tags in Text not working in TextView

Here I try to explain the details why Html tags in Text not working in TextView. At times you may need to display text with Bold and normal style in TextView like this,  …(You may skip to solution )

Html Tags in Text

Welcome, to your favorite music app store.   

So, you’ll define a string in string.xml file as follows

<string name="welcome_text"><b>Welcome,</b> to your favorite music app store.</string>

You’ll apply this wecome_text in a TextView in Java code as below.

TextView tvWelcomeUser=(TextView)findViewById(R.id.tvWelcome);
tvWelcomeUser.setText(R.string.welcome_text);

If you apply setText(int resID) as shown above you can see the text in TextView as expected “Welcome, to your favorite music app store.”

But if you like to display dynamically generated text after Welcome message, as shown below

Welcome, to your favorite music app store. Logged in as: <username>

here <username> is dynamically generated text. You can do this in two ways,

One way is concatenate dynamic text using “+” symol

tvWelcomeUser.setText(getString(R.string.welcome_text) + " Logged in as:" + username);

Another way is defining string in strings.xml file

//in string.xml file
<string name="welcome_text"><b>Welcome,</b> to your favorite music app store. Logged in as: %1$s.</string>

You’ll assign to TextView in Java code like this

//and in Java code
tvWelcomeUser.setText(String.format(getString(R.string.welcome_text),username));

Here comes the issue, In both ways you’ll miss bold text for Welcome text.

even if you try this Html.fromSting(string) method it wont work.

//and in Java code
tvWelcomeUser.setText(Html.fromHtml(String.format(getString(R.string.welcome_text),username)));

You may wondering about this issue, why its not working suddenly which worked before. The reason for this issue is you are converting to String which ignores html tags.

Html tags in Text not working in TextView Solution:

The only solution for this issue is using CData sections for the string in strings.xml file as shown below

//in string.xml file
<string name="welcome_text"><![CDATA[<b>Welcome,</b> to your favorite music app store. Logged in as:]]> %1$s.</string>

Now in Java code you can assign like this,

//and in Java code
String welcomStr=String.format(getString(R.string.welcome_text),username);
tvWelcomeUser.setText(Html.fromHtml(welcomStr));

CData section in string text keeps the html tag data intact even after formatting text using String.format method. So, Html.fromHtml(str) works fine and you’ll see the bold text in Welcome message.

Welcome, to your favorite music app store. Logged in as: <username>

It displays bold text as expected. horray… 🙂

Hope it helps somebody… 😎

You may be also interested in

 

Leave a Reply

Your email address will not be published. Required fields are marked *