Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate line height containing TextView with specific height in Android?

I want to calculate the line (or layout) height (in DP) which contains only TextView as outcome of the TextView text size when using default line spacing ?
I.E. for this layout :

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/minRow1col1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:textIsSelectable="false"
        android:textSize="11dp" />  

</LinearLayout>

What will be the layout/line height ? (any formula ? I don't need the value in run time)

Thanks !

like image 848
SagiLow Avatar asked Nov 27 '13 16:11

SagiLow


2 Answers

I don't know if this help you guys, but my solution to get the height of a line it's independent of the height of the layout, just take the font metrics like this:

myTextView.getPaint().getFontMetrics().bottom - myTextView.getPaint().getFontMetrics().top)

With this you will get the line height and for me, it's works with all words ( there are some chars like "g" or "j" that take some bottom space, the so called "descender" and so on ).

like image 132
jfcogato Avatar answered Nov 15 '22 11:11

jfcogato


Try using the TextPaint object of TextView.

TextView tv = useTextView;
String text = tv.getText().toString();
Paint textPaint = tv.getPaint();

Rect textRect = new Rect();
textPaint.getTextBounds(text, 0, text.length(), textRext);

int textHeight = textRect.height();

Per documentation of Paint#getTextBound:

Return in bounds (allocated by the caller) the smallest rectangle that encloses all of the characters, with an implied origin at (0,0).

Using the Paint object that the TextView uses will ensure it has the same parameters set that will be used to draw the text.

like image 31
DeeV Avatar answered Nov 15 '22 12:11

DeeV