【问题标题】:Add next line to string to be displayed in text view, android?将下一行添加到要在文本视图中显示的字符串,android?
【发布时间】:2015-01-03 06:49:21
【问题描述】:

我有来自服务器的 XML 格式的字符串值。

例如

<rss version="2.0" xmlns:Data="http://www.google.com">
<Data: Mesage="Dear Member,\\nWe wish you and your family a Very Happy New Year 2015./>
</rss?

其中 \\n 代表一个新行。当我将“\n”添加到服务器上的字符串时,它变为“\\n”。

并且在textview中显示为

Dear Member,\\nWe wish you and your family a Very Happy New Year 2015.

我将文本设置为

textview.setText(data_message.replaceAll("\\n", "\n"));
textview.setText(data_message.replaceAll("\\n",System.getProperty("line.separator");

我都试过了。但是下一行没有出现。

如何添加下一行。

@almas

关于使用您的代码。我得到的输出是

Dear Member,\
We wish you and your family a Very Happy New Year 2015.

【问题讨论】:

  • 您应该使用\\\\n 作为匹配模式。请记住 \\ 结果为 \,因此两个转义的反斜杠是 \\\\.

标签: java android xml string textview


【解决方案1】:

问题出在replaceAll方法的第一个参数,也需要转义。 这种结构很丑陋,但工作正常:

    String text = "Dear Member,\\nWe wish you and your family a Very Happy New Year 2015.";
    textView.setText(text.replaceAll("\\\\n", "\n"));

【讨论】:

  • 文本出现在下一行,但留下一个“\”
  • 你使用过完全相同的代码吗?因为,这很奇怪 - 它在理论上有效,在我的设备中有效.. 可能是您留下了一条斜线消息或添加了一条额外的消息?
【解决方案2】:

你可以试试这个,

  String text = "Dear Member,\\nWe wish you and your family a Very Happy New Year 2015.";
  textView.setText(text.replaceAll("\\\n", "/n"));

  String text = "Dear Member,\\nWe wish you and your family a Very Happy New Year 2015.";
  textView.setText(text.replaceAll("\\\n",System.getProperty("line.separator"));

【讨论】:

    【解决方案3】:

    尝试使用replace api,因为您没有使用正则表达式,您的模式如下:

    String data_message = "Dear Member,\\nWe wish you and your family a Very Happy New Year 2015.";
    System.out.println(data_message.replace("\\n", System.getProperty("line.separator")));
    Output:
    Dear Member,
    We wish you and your family a Very Happy New Year 2015.
    

    【讨论】:

    • 它确实有效,但我得到的输出是一个“\”。尊敬的会员,\我们祝您和您的家人 2015 年新年快乐。
    • 您使用的是单反斜杠还是双反斜杠“\\”?如果两次更新有问题的代码。
    • 我使用的是双“\\”
    • 你能用你尝试过的方法更新你的问题吗?它对我有用,所以不知道为什么它不适合你?
    猜你喜欢
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多