Make TextView "\n" ignore paragraph creation

Viewed 173

I have a string of text like this with few newline control characters.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

When I use LeadingMarginSpan on the TextView, it applies after every newline character.

leading margins

^ This is the result I get from applying a LeadingMarginSpan.

enter image description here

^ And this is the result I'd like to have.

Is there any way to ignore paragraphs in TextView so we can just have a normal line break?

3 Answers

Is this what you're looking for?

import android.graphics.Canvas
import android.graphics.Paint
import android.text.Layout
import android.text.style.LeadingMarginSpan

class OnlyFirstParagraphSpan : LeadingMarginSpan {

    private var firstLine : Boolean = true
    private var margin : Int = 32

    override fun getLeadingMargin(first: Boolean) = margin

    override fun drawLeadingMargin(c: Canvas, p: Paint, x: Int, dir: Int, top: Int, baseline: Int, bottom: Int, text: CharSequence, start: Int, end: Int, first:
    Boolean, l: Layout) {
        if (firstLine) {
            margin = 32
            firstLine = false
        } else {
            margin = 0
        }
    }
}

You can apply LeadingMarginSpan.Standard(inset, 0) from 0 to the first new line only, so it doesn't apply to the rest of the paragraphs.

There is no need for using LeadingMarginSpan. You can add "\t" to the fist of your text :

val text = "\t" + "Lorem ipsum dolor sit amet, consectetur adipiscing elit," +
                " sed do eiusmod tempor incididunt ut labore et dolore " +
                "magna aliqua.\nUt enim ad minim veniam, " +
                "quis nostrud exercitation ullamco laboris nisi " +
                "ut aliquip ex ea commodo consequat."
text_view.text = text
Related