Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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

import android.util.Log;

import android.widget.TextView;

public class Main {
    public static String getEllipsisedText(TextView textView) {
        try {
            String text = textView.getText().toString();
            int lines = textView.getLineCount();
            int width = textView.getWidth();
            int len = text.length();

            Log.d("Test", "text-->" + text + "; lines-->" + lines + "; width-->" + width + ";len-->" + len);
            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;
    }
}