I'm trying to use multi-line constants (defined in .xml file under /res/values/ folder), but it seems it's impossible to preserve line breaks there - they all being converted in spaces. I've tried to play with "formatted" attribute of strings (setting it both to "true" and "false", also I've tried wrapping strings in CDATA tags, like this:
<string name="str1">
A
B
C
</string>
<string name="str2" formatted="true">
A
B
C
</string>
<string name="str3" formatted="false">
A
B
C
</string>
<string name="str4"><![CDATA[
A
B
C
]]></string>
<string name="str5" formatted="true"><![CDATA[
A
B
C
]]></string>
<string name="str6" formatted="false"><![CDATA[
A
B
C
]]></string>
All these string declaration variants produce identical results - five-character string "A B C" (line breaks replaced by single space). Is there any way to avoid this?
P.S. I understand that I can use "\n" to insert line breaks, but anyway resulting string will contain spaces in place of actual line-breaks; i.e., following declaration:
<string name="str1">
A\n
B\n
C\n
</string>
results in string "A\n B\n C\n" (every manually inserted line break followed by annoying space). Is there any workaround?..
Add \t for tab and \n for new line.
XML does not require a specific form of line break, so you can use whatever is convenient (carriage return, linefeed, or a combination) when creating an XML file. XML parsers will do the right thing largely because they're parsing on tags, not records - so whatever line break you're using is just whitespace to XML.
Add Line Breaks to a TextView Just add a \n to your text. This can be done directly in your layout file, or in a string resource and will cleanly break the text in your TextView to the next line.
String. xml file contains all the strings which will be used frequently in Android project. String. xml file present in the values folder which is sub folder of res folder in project structure.In Android Studio, we have many Views such as TextView,Button,EditText,CheckBox,RadioButton etc.
In case people are having problems with this, inserting \n
at the end of XML string causes indentation. For example:
<string name="test">
A\n
B\n
C
</string>
Will appear as
A
B
C
Instead, you need to insert \n
at BEGINNING of XML strings
<string name="test">
A
\nB
\nC
</string>
This will cause the new lines to show up properly.
Use another backslash at the end of each line:
<string name="str1">
A\n\
B\n\
C\n\
</string>
This way, you insert line breaks using the "\n" and you escape the line end in the resource file so it is not converted to space.
Still ugly, but it works.
To add a newline from XML, you need to add "\n".
This is how you do it.
<string name="testing">A\nB\nC</string>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lines="4"
android:text="@string/testing"/>
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With