Returns TextView line count. - Android User Interface

Android examples for User Interface:TextView

Description

Returns TextView line count.

Demo Code


//package com.java2s;

import android.graphics.Paint;

import android.graphics.Typeface;
import android.text.TextPaint;

import android.widget.TextView;

public class Main {
    /**//  ww w  . java  2  s .  c  o  m
     * Returns TextView line count.
     * Note that this method will ignore line separator "\n".
     * 
     * @param textView
     * @param textViewWidth
     * @return TextView line count
     */
    public static int getTextViewLineCount(TextView textView,
            int textViewWidth) {
        float textSize = textView.getTextSize();
        Typeface textTypeface = textView.getTypeface(); // may be null.
        TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG
                | Paint.SUBPIXEL_TEXT_FLAG);
        paint.setTextSize(textSize);
        paint.setTypeface(textTypeface);
        int lineCount = 0;
        int index = 0;
        int length = textView.getText().length();
        while (index < length - 1) {
            index += paint.breakText(textView.getText(), index, length,
                    true, textViewWidth, null);
            lineCount++;
        }
        // System.out.println("TextView textSize = " + textSize + ", textTypeface = " + textTypeface + ", lineCount = " + lineCount);
        return lineCount;
    }
}

Related Tutorials