1

This is my xml string...

<string name="my_string">First line.\nSecond line: %1$s.\nThird line.</string>

...which I need to run through String.format without losing the line breaks.

How do I achieve that?

Here is my Java code...

String text = String.format(getString(R.string.my_string, "some text");
Spanned html = Html.fromHtml(text, this, null);
textView.setText(html);

In the xml file, I have tried using \n and <br /> and actual new lines, but none of them produce line breaks in the textView on the UI.

3
  • What's wrong with \n? It's perfect working in my case. I used this string First line. \n Second line: %1$s.\n Third line. Commented Dec 30, 2014 at 12:30
  • If you wan to load string as Html then you have to use <br/> instead \n and replace '<' with '&lt;' in <br/> like : &lt;br/>. Commented Dec 30, 2014 at 12:40
  • \n worked for me when I used it with String.format(String1, String2) Commented Feb 5, 2019 at 12:07

3 Answers 3

2

Try this for HTML string:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="title">Hello&lt;br /&gt;World!</string>
</resources>
Sign up to request clarification or add additional context in comments.

1 Comment

Not required &gt; for ending HTML-escaped string only need &lt;.
0

For using <br />, as its a html tag you must wrap the string in CDATA. Use this.

<string name="my_string"><![CDATA][First line. <br />Second line. <br />Third line.]]</string>

Comments

0
Try to replace '<' with &lt; in HTML-escaped string :

<string name="my_string">First line.&lt;br/>Second line: %1$s.&lt;br/>Third line.</string>

More details check this : http://developer.android.com/guide/topics/resources/string-resource.html

Comments

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.