如何在每个"\ n"之后添加行距在Android中的字符串? [英] How to add line spacing after every "\n" in a string in android?

查看:54
本文介绍了如何在每个"\ n"之后添加行距在Android中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题已经明确说明,我想在Android资源文件中的字符串中定义的每个 \ n 之后添加一个小的行距.

As the question is clearly stated, I want to add a small line spacing after every \n defined in a string in a resource file in Android.

假设我们在xml中定义了这样的字符串:

Let's say we have a string defined in xml like this:

<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 时的正常输出将类似于该图像的左侧.我要实现的是这张图片的右侧.

The normal output when setting it to a TextView will be like the left side of this image. What I want to achieve is the right side of this image.

xml中有一些属性,例如:

There are some attributes in xml like:

android:lineSpacingMultiplier="2"

android:lineSpacingExtra="10dp"

但是这些属性只会导致如下所示:

but these attributes will only lead to something like this:

因此,我不想在每条新行之后添加行距,因为会消耗行的宽度,而只在每定义一个 \ n 之后.

So I don't want to add line spacing after every new line because the width of the line is consumed, but only after every defined \n.

通过代码或html实现我想要的任何方法吗?通过说html,我的意思是这样的,但是在添加< br/> :

Any way to achieve what I want through code or html? By saying html, I mean something like this, but with some modified stuff after adding <br/>:

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标签的原因.

It is more like I want to create many paragraphs in the TextView with small line spacing after each paragraph all in one string. I thought that this would be possible to be done through HTML, so that's why I added html tag.

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

I also don't want to add two line breaks because I only want a small line spacing, and putting two line breaks together will have a large line spacing, which I don't want due to some design issues in my app.

推荐答案

您可以尝试使用此方法:

You can try using this:

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"之后添加行距在Android中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆