Hussein El Feky
Hussein El Feky

Reputation: 6707

How to add line spacing after every "\n" in a string in android?

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.

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>

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.

Image 1

There are some attributes in xml like:

android:lineSpacingMultiplier="2"

and

android:lineSpacingExtra="10dp"

but these attributes will only lead to something like this:

Image 2

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.

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."));

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.


Edit:

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.

Upvotes: 3

Views: 3731

Answers (2)

Fabio Venturi Pastor
Fabio Venturi Pastor

Reputation: 2529

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

Upvotes: 3

Rohit5k2
Rohit5k2

Reputation: 18112

What about giving two line breaks like this

<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>

In case of HTML use two <br/> tags

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."));

Upvotes: 5

Related Questions