How to get line count of textview before rendering?

后端 未结 6 571
南笙
南笙 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:51

    If you know or can determine the width of the TextView's parent, you are able to invoke a view measurement which results in line count being calculated.

    val parentWidth = PARENT_WIDTH // assumes this is known/can be found
    myTextView.measure(
        MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.EXACTLY),
        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
    

    The TextView's layout is no longer null and you can check the calculated line count with myTextView.lineCount.

提交回复
热议问题