186

I am trying to add a line break in the TextView.

I tried suggested \n but that does nothing. Here is how I set my texts.

TextView txtSubTitle = (TextView)findViewById(r.id.txtSubTitle);
txtSubTitle.setText(Html.fromHtml(getResources().getString(R.string.sample_string)));

This is my String: <string name="sample_string">some test line 1 \n some test line 2</string>

It should show like so:

some test line 1
some test line 2

But it shows like so: some test line 1 some test line 2.

Am I missing something?

Janusz
  • 187,060
  • 113
  • 301
  • 369
dropsOfJupiter
  • 6,763
  • 12
  • 47
  • 59
  • have you set android:lines to at least 2? – Robby Pond Mar 21 '11 at 19:24
  • my Subtitle get to up to 6-9 lines already and it does wrap the text to the next line but if i want to break it it does not break. – dropsOfJupiter Mar 21 '11 at 19:36
  • you should post your solution as an answer and accept it, so people can upvote! – bigstones Mar 21 '11 at 20:28
  • 1
    I created a small sample project to illustrate the various ways to encode linebreaks, and their side-effects. Spoiler: `\n` is indeed the best way. https://github.com/paour/StringResourceTest – Pierre-Luc Paour Mar 21 '17 at 10:27
  • The solution is very simple, just remove that `Html.fromHtml()` function and simply use `txtSubTitle.setText(getResources().getString(R.string.sample_string))`. – Bugs Happen May 01 '19 at 04:53

25 Answers25

245

\n works for me, like this:

<TextView android:text="First line\nNext line"
Yuliia Ashomok
  • 8,336
  • 2
  • 60
  • 69
RonN
  • 2,483
  • 2
  • 14
  • 2
108

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

Ali Khaki
  • 1,184
  • 1
  • 13
  • 24
dropsOfJupiter
  • 6,763
  • 12
  • 47
  • 59
78

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");
moffeltje
  • 4,521
  • 4
  • 33
  • 57
Eric JOYÉ
  • 1,077
  • 9
  • 10
67

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.

Verbeia
  • 4,400
  • 2
  • 23
  • 44
dy_
  • 2,433
  • 24
  • 27
  • 3
    i just wanted to add that this quote-stuff also works fine with special characters in string resources or with languages like greek or russian... (if you encounter any problems) – dy_ Jun 19 '12 at 10:09
  • 1
    Thanks, I think using quotes is a better solution to maintain readability for long multi-line texts `"some test line 1 some test line 2 line 3" ` – xinthink Apr 28 '15 at 00:38
  • 1
    Using quotes has other side-effects, such as making spaces always significant (without quotes, multiple spaces in a row, such as in indents, are collapsed). – Pierre-Luc Paour Mar 21 '17 at 10:22
36

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

demongolem
  • 9,474
  • 36
  • 90
  • 105
Robert
  • 631
  • 7
  • 5
28

There are two ways around this. If you use your string as a raw string, you need to use the newline character. If you use it as html, e.g. by parsing it with Html.fromString, the second variant is better.

1) Newline character \n

<string name="sample">This\nis a sample</string>

2) Html newline tag <br> or <br />

<string name="sample">This<br>is a sample</string>
David Passmore
  • 6,089
  • 4
  • 46
  • 70
poitroae
  • 21,129
  • 10
  • 63
  • 81
  • 6
    I didn't downvote it but I think your code is wrong you need "<br>" instead of"
    " it won't work since < is a reserved symbol.
    – JPM Dec 04 '14 at 22:30
  • `
    `, ``, `` and `` tags are allowed in string resources without escape, and are correctly applied by `TextView.setText(resId)`. They are stripped if using `Context.getString(resId)`, unless wrapped in a `CDATA` section.
    – Pierre-Luc Paour Mar 21 '17 at 10:25
17

This worked for me

android:text="First \n Second"
Swayam
  • 16,294
  • 14
  • 64
  • 102
Aniruddha
  • 4,477
  • 2
  • 21
  • 39
16

This worked for me, maybe someone will find out this helpful:

TextView textField = (TextView) findViewById(R.id.textview1);
textField.setText("First line of text" + System.getProperty("line.separator") + "Linija 2");
Zeljko Ivanovic
  • 373
  • 3
  • 5
13

If you're using XML to declare your TextView use android:singleLine = "false" or in Java, use txtSubTitle.setSingleLine(false);

strange quark
  • 5,205
  • 7
  • 41
  • 53
  • no that did not work. Does it have anything to do with Html.fromHtml() and string resources? – dropsOfJupiter Mar 21 '11 at 19:40
  • @dropsOfJupiter : have you looked at what the Html.fromHtml() call is returning? I'd be curious to assign it to a String and look at it in the debugger. – slund Mar 21 '11 at 20:28
11

Used Android Studio 0.8.9. The only way worked for me is using \n. Neither wrapping with CDATA nor <br> or <br /> worked.

9

I use the following:

YOUR_TEXTVIEW.setText("Got some text \n another line");
Carlo Matulessy
  • 975
  • 1
  • 13
  • 27
8

very easy : use "\n"

    String aString1 = "abcd";
    String aString2 = "1234";
    mSomeTextView.setText(aString1 + "\n" + aString2);

\n corresponds to ASCII char 0xA, which is 'LF' or line feed

\r corresponds to ASCII char 0xD, which is 'CR' or carriage return

this dates back from the very first typewriters, where you could choose to do only a line feed (and type just a line lower), or a line feed + carriage return (which also moves to the beginning of a line)

on Android / java the \n corresponds to a carriage return + line feed, as you would otherwise just 'overwrite' the same line

Ronny Webers
  • 5,244
  • 4
  • 28
  • 24
7

As I know in the previous version of android studio uses separate lines " \n " code. But new one (4.1.2) uses "<br/" to separate lines. For example - Old one:

<string name="string_name">Sample text 1 \n Sample text 2 </string>

New one:

<string name="string_name">Sample text 1 <br/> Sample text 2 </string>
6

Try to double-check your localizations. Possible, you trying to edit one file (localization), but actually program using another, just like in my case. The default system language is russian, while I trying to edit english localization.

In my case, working solution is to use "\n" as line separator:

    <string name="string_one">line one.
    \nline two;
    \nline three.</string>
Dr. Failov
  • 311
  • 4
  • 7
6

Also you can add "&lt;br&#47;&gt;" instead of \n.

It's HTML escaped code for <br/>

And then you can add text to TexView:

articleTextView.setText(Html.fromHtml(textForTextView));
mobiledev Alex
  • 2,228
  • 2
  • 28
  • 30
  • nea, dont' think so. Android will actually print that nonesense. I tried. It works well in HTML but not here, especially when you are doing Html.fromHTML("my string from xml file") – dropsOfJupiter Jul 25 '11 at 18:57
  • @drops - Don't forget toString ==> `Html.fromHtml(textForTextView).toString()` --- And then you can do: `articleTextView.setText(Html.fromHtml("text before break
    text after break").toString());` -------- In other words just use `
    ` directly inside `fromHtml()`
    – Peter Ajtai Nov 17 '11 at 23:57
  • `<br/>` should suffice to make sure the style information is not stripped. (based on the official documentation) – jpmcosta Oct 02 '13 at 16:46
3

You could also use the String-Editor of Android Studio, it automatically generates line brakes and stuff like that...

Tim
  • 31
  • 3
2

As Html.fromHtml deprecated I simply I used this code to get String2 in next line.

textView.setText(fromHtml("String1 <br/> String2"));

.

@SuppressWarnings("deprecation")
    public static Spanned fromHtml(String html){
        Spanned result;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
        } else {
            result = Html.fromHtml(html);
        }
        return result;
    }
Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138
2

The most easy way to do it is to go to values/strings (in your resource folder)

Declare a string there:

    <string name="example_string">Line 1\Line2\Line n</string>

And in your specific xml file just call the string like

    <TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/example_string" />
Fidan Gill
  • 63
  • 7
1

I found another method: Is necessary to add the "android:maxWidth="40dp"" attribute. Of course, it may not work perfectly, but it gives a line break.

Master
  • 690
  • 6
  • 18
1

\n was not working for me. I was able to fix the issue by changing the xml to text and building the textview text property like below.

android:text="Line 1
Line 2
Line 3

DoubleSpace"

Hopefully This helps those who have said that \n did not work for them.

Josh Greco
  • 11
  • 2
  • 1
    I'm not convinced this is a good solution. There are just hidden `\n` characters in there. – Almo Mar 01 '18 at 22:05
1

I'm reading my text from a file, so I took a slightly different approach, since adding \n to the file resulted in \n appearing in the text.

    final TextView textView = (TextView) findViewById(R.id.warm_up_view);
    StringBuilder sb = new StringBuilder();
    Scanner scanner = new Scanner(getResources().openRawResource(R.raw.warm_up_file));
    while (scanner.hasNextLine()) {
      sb.append(scanner.nextLine());
      sb.append("\n");
    }

    textView.setText(sb.toString());
Rich Vogt
  • 93
  • 1
  • 9
1

In my case, I solved this problem by adding the following:

android:inputType="textMultiLine"
Cato Minor
  • 2,992
  • 3
  • 29
  • 42
0

Maybe you are able to put the lf into the text, but it doesn't display? Make sure you have enough height for the control. For example:

Correct:

android:layout_height="wrap_content"

May be wrong:

android:layout_height="10dp"
Jarekczek
  • 7,456
  • 3
  • 46
  • 66
0

I would recommend querying the line.separator property, and using that whenever you want to add a line break.

Here is some sample code:

TextView calloutContent = new TextView(getApplicationContext());
calloutContent.setTextColor(Color.BLACK);
calloutContent.setSingleLine(false);
calloutContent.setLines(2);
calloutContent.setText(" line 1" + System.getProperty ("line.separator")+"  line2" );
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
0

I feel like a more complete answer is needed to describe how this works more thoroughly.

Firstly, if you need advanced formatting, check the manual on how to use HTML in string resources.
Then you can use <br/>, etc. However, this requires setting the text using code.

If it's just plain text, there are many ways to escape a newline character (LF) in static string resources.

Enclosing the string in double quotes

The cleanest way is to enclose the string in double quotes.
This will make it so whitespace is interpreted exactly as it appears, not collapsed.
Then you can simply use newline normally in this method (don't use indentation).

<string name="str1">"Line 1.
Line 2.
Line 3."</string>

Note that some characters require special escaping in this mode (such as \").

The escape sequences below also work in quoted mode.

When using a single-line in XML to represent multi-line strings

The most elegant way to escape the newline in XML is with its code point (10 or 0xA in hex) by using its XML/HTML entity &#xA; or &#10;. This is the XML way to escape any character.
However, this seems to work only in quoted mode.

Another method is to simply use \n, though it negatively affects legibility, in my opinion (since it's not a special escape sequence in XML, Android Studio doesn't highlight it).

<string name="str1">"Line 1.&#xA;Line 2.&#10;Line 3."</string>
<string name="str1">"Line 1.\nLine 2.\nLine 3."</string>
<string name="str1">Line 1.\nLine 2.\nLine 3.</string>

Do not include a newline or any whitespace after any of these escape sequences, since that will be interpreted as extra space.

geekley
  • 1,231
  • 10
  • 27