Jono
Jono

Reputation: 18118

Android formatting xml string loses its html tags

I have a xml string below that contains html tags such as Bold and a hyperlink href.

<string name"example"><b>%1$s</b> has been added to your clipboard  and is valid until  <b>%2$s</b><a href="http://www.google.com">Please see our +T\'s and C\'s+ </a>   </string>

when i format the string to dynamically add some values it removes the bolded text and href I defined.

code below:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yy");
Date date = new Date(text.getValidTo()); 
String text = String.format(getString(R.string_dialog_text), text.getCode(), simpleDateFormat.format(date), "£30");

I then apply it to a alert dialog

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setNeutralButton(R.string.ok, onClickListener);
builder.setTitle(title);
builder.setMessage(text);

this worked fine if i dont format the text and directly use the string resource

Upvotes: 5

Views: 1144

Answers (2)

Blackbelt
Blackbelt

Reputation: 157447

use Html.fromHtml

builder.setMessage(Html.fromHtml(text));

when you apply the formatting, the CharSequence is converted back to String, and you need the Spannable with the html information.

From the doc:

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.

try with &lt;b> in place of <b> and with &lt;/b> in place </b>

Upvotes: 7

DJhon
DJhon

Reputation: 1518

Suppose that you want this

<resources>
<string name="our_string_key">
    <B>Title</B> <I>Italic</I><BR/>
    Content
</string>
</resources>

Then in that case you yse it as

textview.setText(Html.fromHtml(R.String.our_string_key));

If in case you are getting errror then you can use it as

   textview.setText(Html.fromHtml(getResources().getString(R.String.our_string_key)));

Upvotes: 0

Related Questions