Search code examples
javaandroidtextviewtext-size

How can I get the height and width values of View's text size in pixels?


I need to get height and width of the textView's text. Yes there is a method called textView.getTextSize(), but I don't understand what that size means: a height, a width or something else? I need the exact width and height values (it will be good, if values will be in pixels not sp).


Solution

  • One approach could be with the use of getPaint() and getTextBound()

    String text = (String) textView.getText();
    Rect textBound = new Rect();
    textView.getPaint().getTextBounds(text,0,text.length(),textBound);
    int textHeight = textBound.height();
    int textWidth = textBound.width();
    

    I am not entirely sure of the height and width being in pixel. Based on this Q&A in regards to RectF, I believe Rect as well should use pixels.