How to get line count of textview before rendering?

后端 未结 6 615
南笙
南笙 2020-12-02 20:29

How can I get the number of lines a string will take up in a TextView before it is rendered.

A ViewTreeObserver will not work because thos

6条回答
  •  天涯浪人
    2020-12-02 20:37

    final Rect bounds = new Rect();
    final Paint paint = new Paint();
    paint.setTextSize(currentTextSize);
    paint.getTextBounds(testString, 0, testString.length(), bounds);
    

    Now divide the width of text with the width of your TextView to get the total number of lines.

    final int numLines = (int) Math.ceil((float) bounds.width() / currentSize);
    

    currentSize : Expected size of the view in which the text will be rendered. The size should not go beyond the screen width.

提交回复
热议问题