5

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

2 Answers 2

7

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Hi i tried this approach and it still could not render he html tags placed on the text
it should be &lt;a and &lt;/a>, shouldn't it?
0

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)));

1 Comment

How you are trying to do it can you post same code.?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.