在安卓中如何在字符串中插入新行

76

我正在创建一个安卓应用程序,在其中有一个按钮将会发送一些信息到电子邮件中,但我不想让所有内容都在一个段落里。

这是我的应用程序针对邮件正文的putExtra所做的事情:

I am the first part of the info being emailed. I am the second part. I am the third part.

这是我的期望:

I am the first part of the info being emailed.
I am the second part.

I am the third part.

如何在字符串中插入换行符或使用 putExtra 方法实现换行?

5个回答

106

尝试:

String str = "my string \n my other string";

打印输出的结果如下:

my string
my other string


1
这不是系统无关的。一些系统使用 \r\n 作为换行符。 - Gibolt
1
@Gibolt 这是独立于操作系统的。Android 只运行在基于 Linux 的设备上,因此换行符在所有设备上都是一致的。 - Johann

92

尝试使用System.getProperty(“line.separator”)来获取一个新行。


16
另外,我学到了在字符串中放置 \n 可以插入一个新行。 - Reed
3
System.getProperty("line.separator") 是跨平台的,而\n则不是。但如果你在开发Android应用程序,则平台是固定的,Linux/Android使用\n作为换行符。 【来源:维基百科/换行符】 - wischi
2
@wischi,说得好。我相信\r\n更具有跨系统兼容性(如果我错了,请纠正我),因此在传输数据时更好。例如,如果您使用\n发送电子邮件,并在使用\r\n的系统上阅读它,则可能会丢失行,而在大多数情况下,如果您将\r\n传递给只需要\n的系统,它会进行补偿。我可能是错的,我没有来源。这只是我随着时间所了解到的。 - Reed

28

我个人更喜欢使用 "\n"。这只是在Linux或Android中插入一个换行符。

例如,

String str = "I am the first part of the info being emailed.\nI am the second part.\n\nI am the third part.";

输出

I am the first part of the info being emailed.
I am the second part.

I am the third part.

一种更通用的方法是使用:

System.getProperty("line.separator")

例如,

String str = "I am the first part of the info being emailed." + System.getProperty("line.separator") + "I am the second part." + System.getProperty("line.separator") + System.getProperty("line.separator") + "I am the third part.";

带来与上面相同的输出。在这里,可以使用System类的静态getProperty()方法获取特定操作系统的"line.seperator"。

但这完全不必要,因为此处的操作系统是固定的,即Android。因此,每次调用方法都是繁重和不必要的操作

此外,这还会增加你的代码长度,使其看起来有点混乱。一个"\n"简单易懂


1
你的字符串中换行符后面有空格,但输出结果中并未显示这些空格,并且输出结果还多了一行空白。 - Matthew Read
@MatthewRead 谢谢,我已经删除了空格。但是我没有看到任何额外的空白行。 - Aritra Roy

10

我在CDATA标记中使用<br>
例如,我的strings.xml文件包含以下项目:

<item><![CDATA[<b>My name is John</b><br>Nice to meet you]]></item>

并打印

My name is John
Nice to meet you

0
如果您想在运行时将换行符添加到从同一字符串派生值的字符串中,则此 Kotlin 代码适用于我:
str = "<br>"+str?.replace("," , "</br><br>")+"</br>"
value = HtmlCompat.fromHtml(${skill_et_1}",Html.FROM_HTML_MODE_LEGACY)
tv.text = value

你在这里使用 val 作为变量,但是 val 是 Kotlin 中的保留关键字。 - Yashovardhan99

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接