Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 228
Jonathan Avatar asked Mar 17 '23 14:03

Jonathan


1 Answers

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>

like image 149
Blackbelt Avatar answered Mar 19 '23 03:03

Blackbelt