سؤال

It doesn't seem like it's possible to add a new line /n to an XML resource string. Is there another way of doing this?

هل كانت مفيدة؟

المحلول

use a blackslash not a forwardslash. "\n"

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Hello\nWorld!</string>
</resources>

Also, if you plan on using the string as HTML, you can use &lt;br /&gt; for a line break(<br />)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">Hello&lt;br /&gt;World!</string>
</resources>

نصائح أخرى

I know this is pretty old question but it topped the list when I searched. So I wanted to update with another method.

In the strings.xml file you can do the \n or you can simply press enter:

<string name="Your string name" > This is your string.

   This is the second line of your string.\n\n Third line of your string.</string>

This will result in the following on your TextView:

This is your string.

This is the second line of your string.

Third line of your string.

This is because there were two returns between the beginning declaration of the string and the new line. I also added the \n to it for clarity, as either can be used. I like to use the carriage returns in the xml to be able to see a list or whatever multiline string I have. My two cents.

This is an old question, but I found that when you create a string like this:

<string name="newline_test">My
New line test</string>

The output in your app will be like this (no newline)

My New line test

When you put the string in quotation marks

<string name="newline_test">"My
New line test"</string>

the newline will appear:

My 
New line test

Hope this helps somebody!

If you put "\n" in a string in the xml file, it's taken as "\\n"

So , I did :

text = text.Replace("\\\n", "\n");   ( text is taken from resX file) 

And then I get a line jump on the screen

When using the translations editor in Android Studio just click the icon to the right (or use Shift-Enter) and then add line breaks using return. This will insert \n correctly in the localized strings.xml.

Very simple you have to just put
\n where ever you want to break line in your string resource.

For example

String s = my string resource have \n line break here;

In the latest version of Android studio, "\n" is going to be printed like it was meant to be there unless the whole string it's in apostrophes

For Example:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title">"Hello\nWorld!"</string>
</resources>

I want to expand on this answer. What they meant is this icon:

Editor window button

It opens a "real editor window" instead of the limited-feature text box in the big overview. In that editor window, special chars, linebreaks etc. are allowed and converted to the correct xml "code" when saved

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top