【问题标题】:How to add line spacing after every "\n" in a string in android?如何在android中的字符串中的每个“\ n”之后添加行距?
【发布时间】:2016-05-12 17:55:27
【问题描述】:

正如问题已明确指出的那样,我想在 Android 资源文件的字符串中定义的每个 \n 之后添加一个小行距。

假设我们在 xml 中定义了一个字符串,如下所示:

<string name="line_test">This is the 1st line. This is still the 1st line.\nThis is the 2nd line.\nThis is the 3rd line. This is still the 3rd line.\nThis is the 4th line.</string>

将其设置为TextView 时的正常输出将类似于此图像的左侧。我想要实现的是这张图片的右侧。

xml中有一些属性,比如:

android:lineSpacingMultiplier="2"

android:lineSpacingExtra="10dp"

但这些属性只会导致这样的结果:

所以我不想在每个新行之后添加行距,因为会消耗行宽,但只能在每个定义的 \n 之后添加。

有什么方法可以通过代码或 html 实现我想要的吗?说html,我的意思是这样的,但是在添加&lt;br/&gt;之后有一些修改:

textView.setText(Html.fromHtml("This is the 1st line. This is still the 1st line.<br/>This is the 2nd line.<br/>This is the 3rd line. This is still the 3rd line.<br/>This is the 4th line."));

这更像是我想在TextView 中创建许多段落,每个段落后的行距很小,都在一个字符串中。我认为这可以通过 HTML 来完成,所以我添加了 html 标签。


编辑:

我也不想添加两个换行符,因为我只想要一个小的行间距,而将两个换行符放在一起会有很大的行间距,由于我的应用程序中的一些设计问题,我不希望这样做.

【问题讨论】:

  • 为什么不给两个换行符? \n\n

标签: android html string newline spacing


【解决方案1】:

这样给两个换行符怎么样

<string name="line_test">This is the 1st line. This is still the 1st line.\n\nThis is the 2nd line.\n\nThis is the 3rd line. This is still the 3rd line.\n\nThis is the 4th line.</string>

如果是HTML,请使用两个&lt;br/&gt; 标签

textView.setText(Html.fromHtml("This is the 1st line. This is still the 1st line.<br/><br/>This is the 2nd line.<br/><br/>This is the 3rd line. This is still the 3rd line.<br/><br/>This is the 4th line."));

【讨论】:

  • 哦对了,我忘了说我不想加两个换行符,因为我只想要一个小的行间距,两个换行符放在一起会有很大的行间距,我由于我的应用程序中的一些设计问题,不想要。我现在编辑了这个问题。但是,我对您的答案投了赞成票,因为它仍然绝对正确。谢谢你的回答。
【解决方案2】:

你可以试试这个:

public String addNewLine(String string) {
    int count = string.split("\n", -1).length - 1;
    StringBuilder sb = new StringBuilder(count);
    String[] splitString = string.split("\n");
    for (int i = 0; i < splitString.length; i++) {
        sb.append(splitString[i]);
        if (i != splitString.length - 1) sb.append("\n\n");
    }
    return sb.toString();
}

【讨论】:

  • 抱歉,没用。甚至没有多行。它只是将整个字符串转换为一行。
  • 试试“\n”然后告诉我
  • 没有任何改变。整个字符串仍然在一行中。
  • 好吧,我得走了,等会儿生病试试别的策略
  • 很高兴能帮助这样一位年轻而有才华的程序员:)
猜你喜欢
  • 1970-01-01
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
  • 2018-09-22
  • 2017-09-11
  • 1970-01-01
相关资源
最近更新 更多