I\'m creating a custom view programmatically that is displaying text that is parsed from an XML file. The text is long and contains the \"/n\" character for force line brea
I also had this problem and I found a really SIMPLE SOLUTION, if setting the text from an XML resources (I know this is not the same as OP, but its worth to know it)
There is no need to add line breaks manually, just add the text as it is BUT quoted.
<string name="test_string">"1. First
2. Second Line
3. Third Line"</string>
I just Use This and now its Work fine for me
message =message.replace("\n","\r\\n");
For line break you use set text view in xml layout this way.
Now is the time
\r\n
for all good men to\r\n
come to the aid of their\r\n
party
try this
fireBody.setText(Html.fromHtml("testing<br>line<\br>")
your server need to send FirstLine<br>lineAfterLineBreak<\br>
I've been having the exact same problem under the exact same circumstances. The solution is fairly straight forward.
When you think about it, since the textview widget is displaying the text with the literal "\n" values, then the string that it is being given must be storing each "\n" like "\\n". So, when your XML string is read and stored, all occurrences of "\n" are being escaped to preserve that text as literal text.
Anyway, all you need to do is:
fireBody.setText(fireText.replace("\\n", "\n"));
Works for me!
To force a line break through the XML of your textview, you need to use \r\n instead of just \n.
So, now your code in the XML becomes
android:text="Now is the time \r\n for all good men to \r\n come to the aid of their \r\n party"
Or if you want to do it programatically, then in your java code :
fireBody.setText("Now is the time \r\n for all good men to \r\n come to the aid of their \r\n party");
You can also declare the text as a string resource value, like this :
<string name="sample_string">"some test line 1 \n some test line 2"</string>
Another easy way to do it would be to change the default attribute of the TextView in your xml file.
<TextView
android:id="@+id/tvContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="false"
/>
And then use, textView.setText("First line \nSecond line \nThird line");