2011-10-22 178 views
11

我有几个情况下,我字符串中的strings.xml是很长,有多条线路\n.如何编辑Android strings.xml文件中的多行字符串?

编辑做不过是很烦人的,因为它是在Eclipse中长线。

是否有更好的方式来编辑它,因此它看起来像稍后将在textview中呈现,即换行符是换行符还是多行编辑模式中的文本?

+2

我不认为你可以做到这一点。但是,如果在使用每个'\ n'时出现错误,应该看起来应该如此。另外,你可以在eclipse中使用'control + i'来组织文本。 – Jong

回答

13

两种可能性:

1.使用源,卢克

XML允许在字符串字面换行符:

<string name="breakfast">eggs 
and 
spam</string> 

你只需要编辑XML代码,而不是使用漂亮Eclipse GUI

2.使用实际文本文件

assets目录中的所有内容均可用作应用程序代码的输入流。

您可以访问资产的那些文件输入流与AssetManager.open(),一个AssetManager实例与Resources.getAssets(),而且......你知道吗,这里是Java的典型极大冗长的代码对于这样一个简单的任务:

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(); 
} 

的使用Scanneris obviously a shortcut米(

+0

+1,尤其是资产小费。适用于我的电子邮件模板。顺便说一句,如果使用Guava,你可以使用'CharStreams.toString(new InputStreamReader(am.open(fileName),Charsets.UTF_8)'''将资源读入字符串。 – Jonik

+0

第一个只适用于将整个字符串放在引号中的情况 – user3533716

10

当然,你可以把换行到XML,但不会给你换行,的strings.xml,在所有的XML文件,Newlines in string content are converted to spaces。因此,声明

<string name="breakfast">eggs 
and 
spam</string> 

将在TextView中被渲染为

eggs and spam 

。幸运的是,在源文件和输出文件中有一个简单的方法可以使用换行符 - 使用\ n代替您的预期输出换行符,并在源文件中转义真正的换行符。上面的声明变得

<string name="breakfast">eggs\n 
and\n 
spam</string> 

其呈现为

eggs 
and 
spam 
+0

不知道\ n \结尾处的额外斜杠是什么?要获得额外的白线,请使用: \ n \ n – Meanman

+0

如果将整个字符串放在引号中,xml中的新行将为您提供换行符。但是,那么xml缩进将在每行之前提供额外的空间。 – user3533716

2

您可以轻松地使用“”,甚至从出错误其他语言写任何字:

<string name="Hello">"Hello world! سلام دنیا!" </string>

0

对于任何正在寻找工作解决方案的人都可以使XML String内容具有多行可维护性并在TextV中呈现多行浏览输出,只需在的新行开头输入\n ...而不是在上一行的末尾。如前所述,XML资源内容中的一行或多行将被转换为一个空白空间。前导,尾随和多个空白空间被忽略。我们的想法是将该空白空间放在上一行的末尾,并将\n置于下一行内容的开头。下面是一个XML字符串例如:

<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 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. 
相关问题