Search code examples
javaandroidkotlinandroid-layouttextview

Calculate a height of specific line of textview


I want to calculate a height of specific textview line. Let's suppose my textview has 3 lines of text and I want to calculate height of the third line. How to achieve that?

I was trying this answer https://stackoverflow.com/a/40133086/21172734 but it gets the whole textview height, am I right?


Solution

  • The answer you referred to computes the whole textView height as you described; if you want to calculate only the height of the third line or any other line, you can use TextView's Layout methods called getLinesBounds.

    Here is how it goes:

    • You get the vertical position or the y-coordinates of that line from the top using getLineTop(), in which you pass 2 as an argument, which means the third line since the index starts from 0.
    • You do the same from the bottom using getLineBottom() with the same argument.
    • You subtract the difference as a final result.

    Here is the full code:

    val thirdLineTop = textView.layout.getLineTop(2)
    val thirdLineBottom = textView.layout.getLineBottom(2)
    val thirdLineHeight = thirdLineBottom - thirdLineTop
    

    I tried that but It raised some errors, the issue is the layout object of the Textview will be null in the onCreate since the TextView hasn't been Laid out YET, so we need to wait until that TextView is laid out and have a valid layout object to start using the above code, so I added a layout observer listner like the following to test the code:

    val tv = findViewById<TextView>(R.id.tva)
    tv.viewTreeObserver.addOnGlobalLayoutListener {
         val thirdLineTop = tv.layout.getLineTop(2)
         val thirdLineBottom = tv.layout.getLineBottom(2)
         println("Total height is $thirdLineBottom - $thirdLineTop")
    }
    

    I hope this would work for you!