create Constrained Static Layout - Android Graphics

Android examples for Graphics:Spannable

Description

create Constrained Static Layout

Demo Code


//package com.java2s;

import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;

public class Main {
    public static StaticLayout createConstrainedStaticLayout(
            TextPaint textpaint, CharSequence charsequence, int i, int j) {
        return createConstrainedStaticLayout(textpaint, charsequence, i, j,
                android.text.Layout.Alignment.ALIGN_NORMAL);
    }//from www. ja v a2  s .  com

    public static StaticLayout createConstrainedStaticLayout(
            TextPaint textpaint, CharSequence charsequence, int i, int j,
            android.text.Layout.Alignment alignment) {
        int k = Math.max(i, 0);
        CharSequence txt = null;
        if (0 == j) {
            txt = "";
        } else if (1 == j) {
            txt = smartEllipsize(charsequence, textpaint, k,
                    android.text.TextUtils.TruncateAt.END);
        } else {
            StaticLayout staticlayout = new StaticLayout(charsequence,
                    textpaint, k, alignment, 1.0F, 0.0F, false);
            if (staticlayout.getLineCount() <= j) {
                return staticlayout;
            }
            int l = staticlayout.getLineEnd(j - 2);
            SpannableStringBuilder spannablestringbuilder = new SpannableStringBuilder(
                    charsequence.subSequence(0, l));
            spannablestringbuilder.append(smartEllipsize(
                    charsequence.subSequence(l, charsequence.length()),
                    textpaint, k, android.text.TextUtils.TruncateAt.END));
            txt = spannablestringbuilder;
        }
        return new StaticLayout(((CharSequence) (txt)), textpaint, k,
                alignment, 1.0F, 0.0F, false);
    }

    public static CharSequence smartEllipsize(CharSequence charsequence,
            TextPaint textpaint, int i,
            android.text.TextUtils.TruncateAt truncateat) {
        String s = charsequence.toString();
        int j = s.indexOf('\r');
        int k = s.indexOf('\n');
        CharSequence charsequence1;
        if (j == -1 && k == -1)
            charsequence1 = charsequence;
        else if (j == -1)
            charsequence1 = charsequence.subSequence(0, k);
        else if (k == -1)
            charsequence1 = charsequence.subSequence(0, j);
        else
            charsequence1 = charsequence.subSequence(0, Math.min(j, k));
        return TextUtils.ellipsize(charsequence1, textpaint, i, truncateat);
    }
}

Related Tutorials