How to edit multiline strings in Android strings.xml file? How to edit multiline strings in Android strings.xml file? android android

How to edit multiline strings in Android strings.xml file?


Two possibilities:

1. Use the Source, Luke

XML allows literal newline characters in strings:

<string name="breakfast">eggsandspam</string>

You just have to edit the XML code instead of using the nifty Eclipse GUI

2. Use actual text files

Everything inside the assets directory is available as a input stream from the application code.

You can access those file input streams of assets with AssetManager.open(), a AssetManager instance with Resources.getAssets(), and… you know what, here’s the Java-typical enormously verbose code for such a simple task:

View view;//before calling the following, get your main//View from somewhere and assign it to "view"String getAsset(String fileName) throws IOException {    AssetManager am = view.getContext().getResources().getAssets();    InputStream is = am.open(fileName, AssetManager.ACCESS_BUFFER);    return new Scanner(is).useDelimiter("\\Z").next();}

the use of Scanner is obviously a shortcut m(


Sure, you could put newlines into the XML, but that won't give you line breaks. In strings.xml, as in all XML files, Newlines in string content are converted to spaces. Therefore, the declaration

<string name="breakfast">eggsandspam</string>

will be rendered as

eggs and spam

in a TextView. Fortunately, there's a simple way to have newlines in the source and in the output - use \n for your intended output newlines, and escape the real newlines in the source. The above declaration becomes

<string name="breakfast">eggs\nand\nspam</string>

which is rendered as

eggsandspam


For anyone looking for a working solution that allows the XML String content to have multiple lines for maintainability and render those multiple lines in TextView outputs, simply put a \n at the beginning of the new line... not at the end of the previous line. As already mentioned, one or more new lines in the XML resource content is converted to one single empty space. Leading, trailing and multiple empty spaces are ignored. The idea is to put that empty space at the end of the previous line and put the \n at the beginning of the next line of content. Here is an XML String example:

<string name="myString">    This is a sentence on line one.    \nThis is a sentence on line two.    \nThis is a partial sentence on line three of the XML    that will be continued on line four of the XML but will be rendered completely on line three of the TextView.    \n\nThis is a sentence on line five that skips an extra line.</string>

This is rendered in the Text View as:

This is a sentence on line one.This is a sentence on line two.This is a partial sentence on line three of the XML that will be continued on line four of the XML but will be rendered completely on line three of the TextView.This is a sentence on line five that skips an extra line.