Returns TextView's text height(text height means line height, not TextView height). - Android User Interface

Android examples for User Interface:TextView

Description

Returns TextView's text height(text height means line height, not TextView height).

Demo Code


import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.TextUtils.TruncateAt;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

public class Main{
    protected static final String TAG = DisplayUtils.class.getSimpleName();
    /**//from w ww .j  a  v a 2  s. c o  m
     * Returns TextView's text height(text height means line height, not TextView height).
     * <p>TextView default size is 14sp. Note that text size is not equal to text width and height.
     * <p>Note that padding is not in calculation scope.
     * <p>Note that TextView.getHeight() is higher than DisplayUtils.getTextHeight().
     * DisplayUtils.getTextHeight() should be equal to TextView.getLineHeight().
     * 
     * @param tv
     * @return text height in pixel(Even though text is empty, it can calculate height).
     */
    public static int getTextHeight(TextView tv) {
        Paint paint = tv.getPaint();
        FontMetrics fm = paint.getFontMetrics();
        float textHeight = fm.descent - fm.ascent;
        Log.v(TAG, "TextView size is " + tv.getTextSize()
                + " sp, textHeight " + textHeight);
        return (int) (textHeight + 0.5f);
    }
}

Related Tutorials