androidtextview

How to increase the spacing between paragraphs in a textview


I have some text that have more than one paragraph (using "\n") and want to put a spacing between the paragraphs, but without using "\n\n". But the text from the same paragraph I want to keep them with a lower space.

I tried using lineSpacingExtra and lineSpacingMultiplier but it sets spaces to every line (insinde the paragraph too).

I want something like this:

Multiparagraph padding


Solution

  • You can use Spannables to achieve this:

    String formattedText = text.replaceAll("\n", "\n\n");
    SpannableString spannableString = new SpannableString(formattedText);
    
    Matcher matcher = Pattern.compile("\n\n").matcher(formattedText);
    while (matcher.find()) {
        spannableString.setSpan(new AbsoluteSizeSpan(25, true), matcher.start() + 1, matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    

    The code above replaces all line breaks with two line breaks. After that, it sets absolute size for each second line break.