get Ellipsised Text in TextView - Android User Interface

Android examples for User Interface:TextView

Description

get Ellipsised Text in TextView

Demo Code


//package com.java2s;

import android.text.TextPaint;
import android.text.TextUtils;

import android.widget.TextView;

public class Main {
    public static String getEllipsisedText(TextView textView) {
        try {//www.  j  a  v a  2s.  co  m
            String text = textView.getText().toString();
            int lines = textView.getLineCount();
            int width = textView.getWidth();
            int len = text.length();

            TextUtils.TruncateAt where = TextUtils.TruncateAt.END;
            TextPaint paint = textView.getPaint();

            StringBuffer result = new StringBuffer();

            int spos = 0, cnt, tmp, hasLines = 0;

            while (hasLines < lines - 1) {
                cnt = paint.breakText(text, spos, len, true, width, null);
                if (cnt >= len - spos) {
                    result.append(text.substring(spos));
                    break;
                }

                tmp = text.lastIndexOf('\n', spos + cnt - 1);

                if (tmp >= 0 && tmp < spos + cnt) {
                    result.append(text.substring(spos, tmp + 1));
                    spos += tmp + 1;
                } else {
                    tmp = text.lastIndexOf(' ', spos + cnt - 1);
                    if (tmp >= spos) {
                        result.append(text.substring(spos, tmp + 1));
                        spos += tmp + 1;
                    } else {
                        result.append(text.substring(spos, cnt));
                        spos += cnt;
                    }
                }

                hasLines++;
            }

            if (spos < len) {
                result.append(TextUtils.ellipsize(
                        text.subSequence(spos, len), paint, (float) width,
                        where));
            }

            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

Related Tutorials