Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a line break in an Android TextView?

\n works for me, like this:

<TextView android:text="First line\nNext line"

ok figured it out:

<string name="sample_string"><![CDATA[some test line 1 <br />some test line 2]]></string>

so wrap in CDATA is necessary and breaks added inside as html tags


Android version 1.6 does not recognize \r\n. Instead, use: System.getProperty("line.separator")

String s = "Line 1"
           + System.getProperty("line.separator")
           + "Line 2"
           + System.getProperty("line.separator");

Linebreaks (\n) only work if you put your string resource value in quotes like this:

<string name="sample_string">"some test line 1 \n some test line 2"</string>

It won't do linebreaks if you put it without quotes like this:

<string name="sample_string">some test line 1 \n some test line 2</string>

yes, it's that easy.


Tried all the above, did some research of my own resulting in the following solution for rendering linefeed escape chars:

string = string.replace("\\\n", System.getProperty("line.separator"));
  1. Using the replace method you need to filter escaped linefeeds (e.g. '\\n')

  2. Only then each instance of line feed '\n' escape chars gets rendered into the actual linefeed

For this example I used a Google Apps Scripting noSQL database (ScriptDb) with JSON formatted data.

Cheers :D